Python爬蟲包 BeautifulSoup 遞歸抓取實例詳解
Python爬蟲包 BeautifulSoup 遞歸抓取實例詳解
概要:
爬蟲的主要目的就是為了沿著網(wǎng)絡抓取需要的內(nèi)容。它們的本質(zhì)是一種遞歸的過程。它們首先需要獲得網(wǎng)頁的內(nèi)容,然后分析頁面內(nèi)容并找到另一個URL,然后獲得這個URL的頁面內(nè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']
上面這個代碼能夠?qū)㈨撁嫔系乃谐溄佣继崛〕鰜怼?/p>
/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是我們不需要的,如側(cè)邊欄、頁眉、頁腳、目錄欄鏈接等等。
所以通過觀察,我們可以發(fā)現(xiàn)所有指向詞條頁面的鏈接都有三個特點:
- 它們都在id是bodyContent的div標簽里
- 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)
其中getLinks的參數(shù)是/wiki/<詞條名稱>,并通過和維基百科的絕對路徑合并得到頁面的URL。通過正則表達式捕獲所有指向其他詞條的URL,并返回給主函數(shù)。
主函數(shù)則通過調(diào)用遞歸getlinks并隨機訪問一條沒有訪問過的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ù)器,或者用其他手段讓代碼在迭代1000次之后還能運行。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
- Python3實現(xiàn)爬蟲爬取趕集網(wǎng)列表功能【基于request和BeautifulSoup模塊】
- python3 BeautifulSoup模塊使用字典的方法抓取a標簽內(nèi)的數(shù)據(jù)示例
- python利用beautifulSoup實現(xiàn)爬蟲
- python爬蟲入門教程--HTML文本的解析庫BeautifulSoup(四)
- python3第三方爬蟲庫BeautifulSoup4安裝教程
- python爬蟲之BeautifulSoup 使用select方法詳解
- Python爬蟲beautifulsoup4常用的解析方法總結
- Python爬蟲包BeautifulSoup簡介與安裝(一)
- Python爬蟲庫BeautifulSoup獲取對象(標簽)名,屬性,內(nèi)容,注釋
- Python爬蟲包BeautifulSoup異常處理(二)
- Python爬蟲包BeautifulSoup實例(三)
- python爬蟲學習筆記之Beautifulsoup模塊用法詳解
相關文章
Python 實現(xiàn)將numpy中的nan和inf,nan替換成對應的均值
這篇文章主要介紹了Python 實現(xiàn)將numpy中的nan和inf,nan替換成對應的均值,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06如何測試Python網(wǎng)站的訪問速度,并且優(yōu)化Python網(wǎng)站的性能
本文使用網(wǎng)絡工具和Python測速庫進行測試Python網(wǎng)站的訪問速度,通過優(yōu)化代碼性能和優(yōu)化服務器性能以及優(yōu)化數(shù)據(jù)庫性能等有針對性地優(yōu)化Python網(wǎng)站的性能2024-01-01