如何获取一个页面内所有URL链接

682次阅读
没有评论

如何获取一个页面内所有URL链接?在Python中可以使用urllib对网页进行爬取,然后利用Beautiful Soup对爬取的页面进行解析,提取出所有的URL。

如何获取一个页面内所有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()方法对匹配的标签进行查找。

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2019-10-09发表,共计1334字。
新手QQ群:570568346,欢迎进群讨论 Python51学习
评论(没有评论)