云萌主云应用官方论坛

标题: python提取页面内的url列表 [打印本页]

作者: 骑单车的小女孩    时间: 2016-12-30 00:46
标题: python提取页面内的url列表
来源:http://www.open-open.com/code/view/1434378966567

  1. from bs4 import BeautifulSoup
  2. import time,re,urllib2

  3. t=time.time()

  4. websiteurls={}

  5. def scanpage(url):
  6.      
  7.     websiteurl=url
  8.     t=time.time()
  9.     n=0
  10.     html=urllib2.urlopen(websiteurl).read()
  11.     soup=BeautifulSoup(html)
  12.     pageurls=[]
  13.     Upageurls={}
  14.     pageurls=soup.find_all("a",href=True)

  15.     for links in pageurls:
  16.         if websiteurl in links.get("href") and links.get("href") not in Upageurls and links.get("href") not in websiteurls:
  17.             Upageurls[links.get("href")]=0
  18.     for links in Upageurls.keys():
  19.         try:
  20.             urllib2.urlopen(links).getcode()
  21.         except:
  22.             print "connect failed"
  23.         else:
  24.             t2=time.time()
  25.             Upageurls[links]=urllib2.urlopen(links).getcode()
  26.             print n,
  27.             print links,
  28.             print Upageurls[links]
  29.             t1=time.time()
  30.             print t1-t2
  31.         n+=1
  32.     print ("total is "+repr(n)+" links")
  33.     print time.time()-t


  34. scanpage("http://news.163.com/")
复制代码







欢迎光临 云萌主云应用官方论坛 (https://www.yunmengzhu.com/) Powered by Discuz! X3.4