logo资料库

Python爬虫获取页面所有URL链接过程详解.pdf

第1页 / 共1页
资料共1页,全文预览结束
爬虫获取页面所有URL链接过程详解 链接过程详解 Python爬虫获取页面所有 主要介绍了Python爬虫获取页面所有URL链接过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者 工作具有一定的参考学习价值,需要的朋友可以参考下 如何获取一个页面内所有URL链接?在Python中可以使用urllib对网页进行爬取,然后利用Beautiful Soup对爬取的页面进行解 析,提取出所有的URL。 什么是什么是Beautiful Soup?? Beautiful Soup提供一些简单的、python式的函数用来处理导航、搜索、修改分析树等功能。它是一个工具箱,通过解析文档 为用户提供需要抓取的数据,因为简单,所以不需要多少代码就可以写出一个完整的应用程序。 Beautiful Soup自动将输入文档转换为Unicode编码,输出文档转换为utf-8编码。你不需要考虑编码方式,除非文档没有指定 一个编码方式,这时,Beautiful Soup就不能自动识别编码方式了。 BeautifulSoup支持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/) 利用BeautifulSoup还可以有针对性的获取网页链接:Python爬虫获取网页上的链接,通过beautifulsoup的findall()方法对匹配 的标签进行查找。 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
分享到:
收藏