欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python爬蟲(chóng)包 BeautifulSoup  遞歸抓取實(shí)例詳解

 更新時(shí)間:2017年01月28日 11:47:41   投稿:lqh  
這篇文章主要介紹了Python爬蟲(chóng)包 BeautifulSoup 遞歸抓取實(shí)例詳解的相關(guān)資料,需要的朋友可以參考下

Python爬蟲(chóng)包 BeautifulSoup  遞歸抓取實(shí)例詳解

概要:

爬蟲(chóng)的主要目的就是為了沿著網(wǎng)絡(luò)抓取需要的內(nèi)容。它們的本質(zhì)是一種遞歸的過(guò)程。它們首先需要獲得網(wǎng)頁(yè)的內(nèi)容,然后分析頁(yè)面內(nèi)容并找到另一個(gè)URL,然后獲得這個(gè)URL的頁(yè)面內(nèi)容,不斷重復(fù)這一個(gè)過(guò)程。

讓我們以維基百科為一個(gè)例子。

我們想要將維基百科中凱文·貝肯詞條里所有指向別的詞條的鏈接提取出來(lái)。

# -*- coding: utf-8 -*-
# @Author: HaonanWu
# @Date:  2016-12-25 10:35:00
# @Last Modified by:  HaonanWu
# @Last Modified time: 2016-12-25 10:52:26
from urllib2 import urlopen
from bs4 import BeautifulSoup

html = urlopen('http://en.wikipedia.org/wiki/Kevin_Bacon')
bsObj = BeautifulSoup(html, "html.parser")

for link in bsObj.findAll("a"):
  if 'href' in link.attrs:
    print link.attrs['href']

上面這個(gè)代碼能夠?qū)㈨?yè)面上的所有超鏈接都提取出來(lái)。

/wiki/Wikipedia:Protection_policy#semi
#mw-head
#p-search
/wiki/Kevin_Bacon_(disambiguation)
/wiki/File:Kevin_Bacon_SDCC_2014.jpg
/wiki/San_Diego_Comic-Con
/wiki/Philadelphia
/wiki/Pennsylvania
/wiki/Kyra_Sedgwick

首先,提取出來(lái)的URL可能會(huì)有一些重復(fù)的

其次,有一些URL是我們不需要的,如側(cè)邊欄、頁(yè)眉、頁(yè)腳、目錄欄鏈接等等。

所以通過(guò)觀察,我們可以發(fā)現(xiàn)所有指向詞條頁(yè)面的鏈接都有三個(gè)特點(diǎn):

  • 它們都在id是bodyContent的div標(biāo)簽里
  • URL鏈接不包含冒號(hào)
  • URL鏈接都是以/wiki/開(kāi)頭的相對(duì)路徑(也會(huì)爬到完整的有http開(kāi)頭的絕對(duì)路徑)
from urllib2 import urlopen
from bs4 import BeautifulSoup
import datetime
import random
import re

pages = set()
random.seed(datetime.datetime.now())
def getLinks(articleUrl):
  html = urlopen("http://en.wikipedia.org"+articleUrl)
  bsObj = BeautifulSoup(html, "html.parser")
  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"]
  if newArticle not in pages:
    print(newArticle)
    pages.add(newArticle)
    links = getLinks(newArticle)

其中g(shù)etLinks的參數(shù)是/wiki/<詞條名稱>,并通過(guò)和維基百科的絕對(duì)路徑合并得到頁(yè)面的URL。通過(guò)正則表達(dá)式捕獲所有指向其他詞條的URL,并返回給主函數(shù)。

主函數(shù)則通過(guò)調(diào)用遞歸getlinks并隨機(jī)訪問(wèn)一條沒(méi)有訪問(wèn)過(guò)的URL,直到?jīng)]有了詞條或者主動(dòng)停止為止。

這份代碼可以將整個(gè)維基百科都抓取下來(lái)

from urllib.request import urlopen
from bs4 import BeautifulSoup
import re

pages = set()
def getLinks(pageUrl):
  global pages
  html = urlopen("http://en.wikipedia.org"+pageUrl)
  bsObj = BeautifulSoup(html, "html.parser")
  try:
    print(bsObj.h1.get_text())
    print(bsObj.find(id ="mw-content-text").findAll("p")[0])
    print(bsObj.find(id="ca-edit").find("span").find("a").attrs['href'])
  except AttributeError:
    print("This page is missing something! No worries though!")

  for link in bsObj.findAll("a", href=re.compile("^(/wiki/)")):
    if 'href' in link.attrs:
      if link.attrs['href'] not in pages:
        #We have encountered a new page
        newPage = link.attrs['href']
        print("----------------\n"+newPage)
        pages.add(newPage)
        getLinks(newPage)
getLinks("") 

一般來(lái)說(shuō)Python的遞歸限制是1000次,所以需要人為地設(shè)置一個(gè)較大的遞歸計(jì)數(shù)器,或者用其他手段讓代碼在迭代1000次之后還能運(yùn)行。

感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!

相關(guān)文章

最新評(píng)論