如何获取一个页面中的所有URL链接?在Python中,可以用urllib对网页进行抓取,然后用BeautifulSoup对抓取的网页进行解析,提取所有的URL。
什么是BeautifulSoup
美丽汤提供了一些简单的类似python的函数来处理导航、搜索、修改分析树等功能。它是一个工具箱,为用户提供了可以通过解析文档来抓取的数据。因为简单,不用太多代码就能写出完整的应用。
BeautifulSoup自动将输入文档转换为Unicode编码,将输出文档转换为utf-8编码。不需要考虑编码方式,除非文档没有指定编码方式,否则无法自动识别编码方式。
美化组支持Python标准库中的HTML解析器和一些第三方解析器。如果不安装,Python会用Python默认解析器,lxml解析器更强大更快。
具体代码如下:
from bs4 import BeautifulSoup import time,re,urllib2 t=time.time() websiteurls={} def scanpage(url): websiteurl=url t=time.time() n=0 html=urllib2.urlopen(websiteurl).read() soup=BeautifulSoup(html) pageurls=[] Upageurls={} pageurls=soup.find_all("a",href=True) for links in pageurls: if websiteurl in links.get("href") and links.get("href") not in Upageurls and links.get("href") not in websiteurls: Upageurls[links.get("href")]=0 for links in Upageurls.keys(): try: urllib2.urlopen(links).getcode() except: print "connect failed" else: t2=time.time() Upageurls[links]=urllib2.urlopen(links).getcode() print n, print links, print Upageurls[links] t1=time.time() print t1-t2 n+=1 print ("total is "+repr(n)+" links") print time.time()-t scanpage(http://news.163.com/)
评论列表