Python网络数据采集5(译者:哈雷)

来源:互联网 发布:linux系统调用过程 编辑:程序博客网 时间:2024/04/27 18:09

第三章 开始爬取数据
以wiki中kevin Bacon 页面作为爬取对象,然后选取其中指向特定的网页再次爬取。示例如下
[python]代码片

from urllib.request import urlopen  from bs4 import BeautifulSoup  import datetime  import random  import re  random.seed(datetime.datetime.now())#随机种子  def getLinks(articleUrl):      html = urlopen("http://en.wikipedia.org"+articleUrl)      bsObj = BeautifulSoup(html)      return bsObj.find("div", {"id":"bodyContent"}).findAll("a",href=re.compile("^(/wiki/)((?!:).)*$"))  links = getLinks("/wiki/Kevin_Bacon")  while len(links) > 0:      newArticle = links[random.randint(0, len(links)-1)].attrs["href"]#随机选取一个网页爬取      print(newArticle)      links = getLinks(newArticle)  
     利用scrapy爬取数据的方法暂时先不介绍。
0 0
原创粉丝点击