python庫學習筆記——BeautifulSoup處理子標簽、后代標簽、兄弟標簽和父標簽


首先,我們來看一個簡單的網頁https://www.pythonscraping.com/pages/page3.html,打開后:

右鍵“檢查”(谷歌瀏覽器)查看元素:


用導航樹的形式簡單表示出來:


可知:

tr是table的子標簽

tr、th、td、img、span標簽都是table的后代標簽


一般情況下,bbs0bj.body.h1選擇的是body標簽后代里的第一個h1標簽,不會去找body外面的標簽

類似的,bs0bj.div.findall("img")會找到第一個div標簽,然后獲取這個div后代里面所有的img標簽

1. 處理子標簽和后代標簽

如果你想獲得子標簽,可以用.children標簽:

from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html)

for child in bsObj.find("table",{"id":"giftList"}).children:
    print(child)

部分結果如下:


如果你用descendants()函數,就會獲得每個后代標簽


2. 處理兄弟標簽

BeautifulSoup中的next_siblings()很擅長處理帶標題行的表格:
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html, "html.parser")

for sibling in bsObj.find("table",{"id":"giftList"}).tr.next_siblings:
    print(sibling) 
得到部分結果如下:


如果你很擅長找到一組兄弟標簽中的最后一個標簽,那么previous_siblings()函數
另外,next_sibling(),previous_siblings()返回單個標簽

3. 處理父親標簽

抓取網頁的時候,父標簽用到的很少,用parent和parents抓取,舉個例子:
from urllib.request import urlopen
from bs4 import BeautifulSoup

html = urlopen("http://www.pythonscraping.com/pages/page3.html")
bsObj = BeautifulSoup(html, "html.parser")
print(bsObj.find("img",{"src":"../img/gifts/img1.jpg"}).parent.previous_sibling.get_text())
輸出:
$15.00
 
         
可以這樣理解:
 
         
 (1)選擇圖片標簽 
        
(2)選擇圖片標簽的父標簽<td>
(3)選擇 標簽<td>前面的一個兄弟標簽
(4)選擇標簽中的文字

參考資料:《python網絡數據采集》

$15.00


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM