Python爬蟲包 BeautifulSoup? 遞歸抓取實(shí)例詳解
概要:
爬蟲的主要目的就是為了沿著網(wǎng)絡(luò)抓取需要的內(nèi)容。它們的本質(zhì)是一種遞歸的過程。它們首先需要獲得網(wǎng)頁的內(nèi)容,然后分析頁面內(nèi)容并找到另一個URL,然后獲得這個URL的頁面內(nèi)容,不斷重復(fù)這一個過程。
讓我們以維基百科為一個例子。
我們想要將維基百科中凱文?貝肯詞條里所有指向別的詞條的鏈接提取出來。
# -*- 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']
上面這個代碼能夠?qū)㈨撁嫔系乃谐溄佣继崛〕鰜怼?
/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
首先,提取出來的URL可能會有一些重復(fù)的
其次,有一些URL是我們不需要的,如側(cè)邊欄、頁眉、頁腳、目錄欄鏈接等等。
所以通過觀察,我們可以發(fā)現(xiàn)所有指向詞條頁面的鏈接都有三個特點(diǎn):
- 它們都在id是bodyContent的div標(biāo)簽里
- URL鏈接不包含冒號
-
URL鏈接都是以/wiki/開頭的相對路徑(也會爬到完整的有http開頭的絕對路徑)
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/<詞條名稱>,并通過和維基百科的絕對路徑合并得到頁面的URL。通過正則表達(dá)式捕獲所有指向其他詞條的URL,并返回給主函數(shù)。
主函數(shù)則通過調(diào)用遞歸getlinks并隨機(jī)訪問一條沒有訪問過的URL,直到?jīng)]有了詞條或者主動停止為止。
這份代碼可以將整個維基百科都抓取下來
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("")
一般來說Python的遞歸限制是1000次,所以需要人為地設(shè)置一個較大的遞歸計數(shù)器,或者用其他手段讓代碼在迭代1000次之后還能運(yùn)行。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
