首頁  >  文章  >  後端開發  >  Python爬蟲包 BeautifulSoup 遞歸抓取實例詳解

Python爬蟲包 BeautifulSoup 遞歸抓取實例詳解

高洛峰
高洛峰原創
2017-02-03 15:59:292235瀏覽

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: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']

   

上面這個程式碼能夠將頁面上的所有超連結都提取出來。

/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 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的參數是/wiki/,並透過和維基百科的絕對路徑合併得到頁面的URL。透過正規表示式捕捉所有指向其他詞條的URL,並傳回給主函數。

主函數則透過呼叫遞歸getlinks並隨機存取一條沒有存取過的URL,直到沒有了詞條或主動停止為止。

這份程式碼可以將整個維基百科都抓取下來

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次,所以需要人為地設定一個較大的遞歸計數器,或是用其他手段讓程式碼在迭代1000次之後還能運行。

感謝閱讀,希望能幫助大家,謝謝大家對本站的支持!

更多Python爬蟲包 BeautifulSoup 遞歸抓取實例詳解相關文章請關注PHP中文網!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn