当前位置:Gxlcms > Python > python提取页面内url列表的方法

python提取页面内url列表的方法

时间:2021-07-01 10:21:17 帮助过:84人阅读

本文实例讲述了python提取页面内url列表的方法。分享给大家供大家参考。具体实现方法如下:

  1. from bs4 import BeautifulSoup
  2. import time,re,urllib2
  3. t=time.time()
  4. websiteurls={}
  5. def scanpage(url):
  6. websiteurl=url
  7. t=time.time()
  8. n=0
  9. html=urllib2.urlopen(websiteurl).read()
  10. soup=BeautifulSoup(html)
  11. pageurls=[]
  12. Upageurls={}
  13. pageurls=soup.find_all("a",href=True)
  14. for links in pageurls:
  15. if websiteurl in links.get("href") and links.get("href") not in Upageurls and links.get("href") not in websiteurls:
  16. Upageurls[links.get("href")]=0
  17. for links in Upageurls.keys():
  18. try:
  19. urllib2.urlopen(links).getcode()
  20. except:
  21. print "connect failed"
  22. else:
  23. t2=time.time()
  24. Upageurls[links]=urllib2.urlopen(links).getcode()
  25. print n,
  26. print links,
  27. print Upageurls[links]
  28. t1=time.time()
  29. print t1-t2
  30. n+=1
  31. print ("total is "+repr(n)+" links")
  32. print time.time()-t
  33. scanpage("http://news.163.com/")

希望本文所述对大家的Python程序设计有所帮助。

人气教程排行