Python爬蟲包 BeautifulSoup 遞歸抓取實例詳解
概要:
爬蟲的主要目的就是為了沿著網絡抓取需要的內容。它們的本質是一種遞歸的過程。它們首先需要獲得網頁的內容,然后分析頁面內容并找到另一個URL,然后獲得這個URL的頁面內容,不斷重復這一個過程。
讓我們以維基百科為一個例子。
我們想要將維基百科中凱文·貝肯詞條里所有指向別的詞條的鏈接提取出來。
# -*- coding: utf-8 -*-# @Author: HaonanWu# @Date: 2016-12-25 10:35:00# @Last Modified by: HaonanWu# @Last Modified time: 2016-12-25 10:52:26from urllib2 import urlopenfrom bs4 import BeautifulSouphtml = 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']上面這個代碼能夠將頁面上的所有超鏈接都提取出來。
/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可能會有一些重復的
其次,有一些URL是我們不需要的,如側邊欄、頁眉、頁腳、目錄欄鏈接等等。
所以通過觀察,我們可以發現所有指向詞條頁面的鏈接都有三個特點:
它們都在id是bodyContent的div標簽里 URL鏈接不包含冒號 URL鏈接都是以/wiki/開頭的相對路徑(也會爬到完整的有http開頭的絕對路徑)from urllib2 import urlopenfrom bs4 import BeautifulSoupimport datetimeimport randomimport repages = 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)其中getLinks的參數是/wiki/<詞條名稱>,并通過和維基百科的絕對路徑合并得到頁面的URL。通過正則表達式捕獲所有指向其他詞條的URL,并返回給主函數。
主函數則通過調用遞歸getlinks并隨機訪問一條沒有訪問過的URL,直到沒有了詞條或者主動停止為止。
這份代碼可以將整個維基百科都抓取下來
from urllib.request import urlopenfrom bs4 import BeautifulSoupimport repages = 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("")
新聞熱點
疑難解答