本文為本人讀《Python網(wǎng)絡(luò)數(shù)據(jù)采集》寫下的筆記赁温。在第一章和第二章中,作者主要講了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。前兩行導(dǎo)入了requests庫和BeautifulSoup庫谍婉,后面3行分別是:發(fā)送一個請求并返回一個response對象舒憾,使用BeautifulSoup構(gòu)建一個BeautifulSoup對象并html.parser解析器解析response的返回值,最后打印h1屡萤。然而珍剑,這段代碼完全沒有可靠性,一旦發(fā)生異常則程序無法運行死陆。
更好的做法是加入異常的捕獲:
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寫錯或者屬性尋找錯誤唧瘾,程序都可以繼續(xù)執(zhí)行,并提示錯誤别凤。
第二章(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來尋找孩子節(jié)點和子孫節(jié)點
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
注意孩子節(jié)點只為table下一層結(jié)點,如table > tr规哪,而table > tr > img則不包含
for child in soup.find("table",{"id":"giftList"}).descendants:
print child
包含table下的所有節(jié)點求豫,即子孫結(jié)點
使用兄弟結(jié)點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標簽?zāi)兀吭蚴莕ext_siblings找到的是當前節(jié)點的后面的兄弟標簽诉稍,而不包括標簽本身蝠嘉。
如果文章有什么寫的不好或者不對的地方,麻煩留言哦1蕖T楦妗!