本文為本人讀《Python網絡數據采集》寫下的筆記。在第一章和第二章中,作者主要講了BeautifulSoup這個第三方庫的使用方法,以下為書中提到的比較有意思的示例(注:作者使用的是python3.x,而我使用的是python2.x;作者使用urllib庫,我使用的是requests,但對學習BeautifulSoup并沒有影響):
第一章:
BeautifulSoup簡單的使用:
import requests
from bs4 import BeautifulSoup as bs
resp = requests.get(url='http://www.pythonscraping.com/pages/page1.html')
soup = bs(resp.content, 'html.parser')
print soup.h1
上述代碼是一個簡單的demo。前兩行導入了requests庫和BeautifulSoup庫,后面3行分別是:發送一個請求并返回一個response對象,使用BeautifulSoup構建一個BeautifulSoup對象并html.parser解析器解析response的返回值,最后打印h1。然而,這段代碼完全沒有可靠性,一旦發生異常則程序無法運行。
更好的做法是加入異常的捕獲:
import requests
from bs4 import BeautifulSoup as bs
from requests.packages.urllib3.connection import HTTPConnection
def getTitle(url):
try:
resp = requests.get(url=url)
soup = bs(resp.content, 'html.parser')
title = soup.h1
except HTTPConnection as e:
print e
except AttributeError as e:
return None
return title
title = getTitle('http://www.pythonscraping.com/pages/page1.html')
if title == None:
print("title could not be found")
else:
print(title)
上述代碼使用了異常的捕獲,一旦url寫錯或者屬性尋找錯誤,程序都可以繼續執行,并提示錯誤。
第二章(BeautifulSoup進價)
使用findAll查找標簽包含class屬性為green或red的所有標簽
import requests
from bs4 import BeautifulSoup as bs
resp = requests.get(url='http://www.pythonscraping.com/pages/warandpeace.html')
soup = bs(resp.content, 'html.parser')
for name in soup.findAll('span': {'class': {'green', "red"}}):
print name.get_text()
注意上述中字典的使用方法,soup.findAll('span': {'class': {'green'}})也可以使用soup.findAl(_class='green')來代替
使用children和descendants來尋找孩子節點和子孫節點
resp = requests.get(url='http://www.pythonscraping.com/pages/page3.html')
soup = bs(resp.content, 'html.parser')
for child in soup.find("table",{"id":"gitfList"}).children:
print child
注意孩子節點只為table下一層結點,如table > tr,而table > tr > img則不包含
for child in soup.find("table",{"id":"giftList"}).descendants:
print child
包含table下的所有節點,即子孫結點
使用兄弟結點next_siblings過濾table下的th標簽:
resp = requests.get(url='http://www.pythonscraping.com/pages/page3.html')
soup = bs(resp.content, 'html.parser')
for child in soup.find("table",{"id":"giftList"}).tr.next_siblings:
print child
注意:為何next_siblings能過濾th標簽呢?原因是next_siblings找到的是當前節點的后面的兄弟標簽,而不包括標簽本身。
如果文章有什么寫的不好或者不對的地方,麻煩留言哦!!!