1. 程式人生 > >python爬蟲(一)BeautifulSoup簡介

python爬蟲(一)BeautifulSoup簡介

BeautifulSoup庫的名字取自劉易斯·卡羅爾在《愛麗絲漫遊仙境》裡的同名詩歌。BeautifulSoup通過定位HTML標籤來格式化和組織複雜的網路資訊,用簡單易用的python物件展現XML結構資訊。

一、安裝Beautifulsoup

1、windows平臺

①安裝pip(安裝python3時選擇安裝)
②利用pip安裝bs4——命令列模式:`pip install BeautifulSoup4

二、執行Beautifulsoup

解析本地網頁

from bs4 import BeautifulSoup #bs4是BeautifulSoup4的簡稱

with open(r'E:\PycharmProjects\web_prase\new_index.html'
) as web_data:#利用open函式開啟本地網頁檔案 soup=BeautifulSoup(web_data.read(),'lxml')#利用lxml解析網頁 print(soup.h2)

輸出結果為:

<h2>Article</h2>

解析線上網頁

from bs4 import BeautifulSoup
import requests

url='https://cn.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html'
web_data=requests.get(url)#利用requests庫爬取線上網頁
soup=BeautifulSoup(web_data.text,'lxml') print(soup)

或者

from bs4 import BeautifulSoup
from urllib.request import urlopen

html=urlopen('https://cn.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html')#利用urllib模組爬取線上網頁
soup=BeautifulSoup(html.read(),'lxml')

三、可靠的網路連線

html=urlopen('https://cn.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html'
)

這行程式碼主要可能會發生兩種異常:

  1. 網頁在伺服器上不存在(或者獲取頁面的時候出現錯誤)
  2. 伺服器不存在

第一種異常發生時,程式會返回HTTP錯誤。HTTP錯誤可能是“404 Page Not Found”、“500 Internal Sever Error”等。所有類似情形,urlopen都會丟擲“HTTPError”異常。可以用下面的方式處理這種異常:

try:
    html=urlopen('https://cn.tripadvisor.com/Attractions-g60763-Activities-New_York_City_New_York.html')
except HTTPError as e:
    print(e)
    #返回空值,中斷程式,或者執行另一個方案
else#程式繼續。
if html is None:
    print("URL is not found")
else:
    #程式繼續

四、複雜HTML解析

從複雜的網頁中尋覓資訊時,在找到目標資訊之前,需要“敲掉”網頁上那些不需要的資訊。

通過屬性查詢標籤的方法

CSS可以讓HTML元素呈現出差異化,使那些具有完全相同修飾的元素呈現出不同的樣式。比如,有一些標籤看起來是這樣:

<span>class="green"</span>

而另一些標籤看起來是這樣:

<span>class="red"</span>

網路爬蟲可以通過class屬性的值,輕鬆地區分出兩種不同的標籤。

標籤組的使用

標籤解析樹的導航過程