標籤:find child descendant sibling parent
1、通過的名稱和屬性尋找標籤
和之前一樣,抓取整個頁面,然後建立一個BeautifulSoup對象。這裡面“lxml”解析器需要另外下載。
pip3 install lxml
>>> from urllib.request import urlopen>>> from bs4 import BeautifulSoup>>> html = urlopen("http://www.pythonscraping.com/pages/warandpeace.html")>>> bsObj = BeautifulSoup(html, "lxml")
finAll()可以擷取頁面中所有指定的標籤,抽取只包含在<span class="green"></span>標籤裡的文字,這樣就會得到一個人物名稱的列表。.get_text()會把所有的標籤都清除,返回一個只包含文字的字串。
>>> nameList = bsObj.findAll("span", {"class":"green"})>>> for name in nameList: print(name.get_text())
2、詳解finAll()和find()的參數
findAll(tag, attributes, recursive, text, limit, keywords)
find(tag, attributes, recursive, text, keywords)
tag--可以傳一個標籤的名稱或多個標籤名稱組成的列表做參數;如下樣本將返回一個包含HTML文檔中所有標題標籤的列表
>>> bsObj.findAll({"h1", "h2", "h3", "h4", "h5", "h6"})[<h1>War and Peace</h1>, <h2>Chapter 1</h2>]
attributes--字典封裝一個標籤的若干屬性和對應的屬性值;如下樣本會返回HTML文檔裡紅色與綠色兩種顏色的span標籤
>>> bsObj.findAll("span", {"class":{"green", "red"}})
recursive--布爾變數(預設為True)尋找標籤參數的所有子標籤,及子標籤的子標籤;為False時,只尋找文檔的一級標籤
text--是用標籤的常值內容去匹配;如下樣本作用是尋找網頁中包含“the prince”內容的標籤數量
>>> nameList=bsObj.findAll(text="the prince")>>> print(len(nameList))7
limit--按照網頁上的順序排序,擷取的前 x 項結果(等於1時等價於find)
keywords--可以讓你選擇那些具有指定屬性的標籤
>>> allText = bsObj.findAll(id="text")>>> print(allText[0].get_text())
下面兩行代碼是完全一樣的
bsObj.findAll(id="text")bsObj.findAll("", {"id":"text"})
由於class為關鍵字,使用keywords指定時需要多加一個底線
bsObj.findAll(class_="green")bsObj.findAll("", {"class":"green"})
3、BeautifulSoup對象
BeautifulSoup對象:如前面程式碼範例中的bsObj
Tag對象:BeautifulSoup對象通過find和findAll或直接調用子標籤擷取的一列象或單個對象(如bsObj.div.h1)
NavigableString對象:表示標籤裡的文字
Comment對象:尋找 HTML 文檔的注釋標籤
4、標籤解析樹的導航:通過標籤在文檔中的位置來尋找標籤。
處理子標籤與後代標籤:
子標籤(child)是一個父標籤的下一級。
後代標籤(descendant)是指一個父標籤下面所有層級的標籤。
同樣的
>>> from urllib.request import urlopen>>> from bs4 import BeautifulSoup>>> html = urlopen("http://www.pythonscraping.com/pages/page3.html")>>> bsObj = BeautifulSoup(html, "lxml")
只想找出子標籤,可以用.children;如下樣本會列印giftList表格中所有產品的資料行(如使用.descendants將列印出二十幾個標籤)
>>> for child in bsObj.find("table", {"id":"giftList"}).children:print(child)
處理兄弟標籤:
next_siblings和previous_siblings將返回一組標籤
next_sibling和previous_sibling將返回單個標籤
如下樣本會列印產品列表裡除第一行外的所有行的產品
>>> for sibling in bsObj.find("table", {"id":"giftList"}).tr.next_siblings: print(sibling)
處理父標籤:
parent 和 parents
如下樣本會列印出指定圖片對應的商品價格
>>> print(bsObj.find("img", {"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text())$15.00
《Python網路資料擷取》讀書筆記(二)