3. 1子節(jié)點(diǎn)和子孫節(jié)點(diǎn)
soup.body.h1# 選中body 標(biāo)簽下的h1沪羔,這個(gè)h1 標(biāo)簽是body標(biāo)簽的子節(jié)點(diǎn)
同理苟鸯,soup.div.find_all('img')會(huì)找到所有div里面的img標(biāo)簽。
.children 和.descendants
對(duì)比代碼如下:
html = urlopen('http://www.pythonscraping.com/pages/page3.html')
soup = BeautifulSoup(html, 'lxml')
children = soup.find('table',{'id':'giftList'}).children
descendants = soup.find('table',{'id':'giftList'}).descendants
sum = 0
for child in children:
print(child)
sum +=1
print(sum)
sum2 = 0
for descendant in descendants:
sum2+=1
print(descendant)
print(sum2)
運(yùn)行結(jié)果可知 sum = 13, sum2 = 86
取descendants的第一部分作比較可以發(fā)現(xiàn)
<tr><th>#=============<tr>是soup.find('table',{'id':'giftList'})的子節(jié)點(diǎn)====
Item Title
</th><th>
Description
</th><th>
Cost
</th><th>
Image
</th></tr>#============<tr>是soup.find('table',{'id':'giftList'})的子節(jié)點(diǎn)====
<th> #============<th>是<tr>的子節(jié)點(diǎn)稽荧,('table',{'id':'giftList'})的子孫節(jié)點(diǎn)==
Item Title
</th> #============<th>是<tr>的子節(jié)點(diǎn),('table',{'id':'giftList'})的子孫節(jié)點(diǎn)==
Item Title#=========文本是<th>標(biāo)簽的內(nèi)容,也是子孫節(jié)點(diǎn)================
<th>#============同上====================
Description
</th>
Description
<th>
Cost
</th>
Cost
....
對(duì)比可知窗怒,children只列出了<tr>標(biāo)簽所包含的內(nèi)容。而descendants列出了所有包含的標(biāo)簽節(jié)點(diǎn)以及文本蓄拣,即<tr>子標(biāo)簽中的所有子子孫孫標(biāo)簽都會(huì)查找返回扬虚。
3.2 父節(jié)點(diǎn)
通常情況下我們更經(jīng)常查找子節(jié)點(diǎn),而在某些特定情況下會(huì)用到查詢(xún)父節(jié)點(diǎn)球恤,.parents 和 .parent辜昵。
from urllib.request import urlopen
from bs4 import BeautifulSoup
html = urlopen('http://www.pythonscraping.com/pages/warandpeace.html')
soup = BeautifulSoup(html)
print(soup.find('img', {'src':'../img/gifts/img1.jpg'}).parent.previous_sibling.get_text())
分析一下代碼是如何工作的。
<tr>
--<td>
--<td>(3)
--"$15.00"(4)
--s<td>(2)
--<img src="../img/gifts/img1.jpg">(1)
1.首先定位到含src="../img/gifts/img1.jpg"的標(biāo)簽img咽斧。
2.選中img標(biāo)簽的父節(jié)點(diǎn)s<td>.
3.選中s<td>的上一個(gè)同層級(jí)標(biāo)簽<td>
4.選取<td>標(biāo)簽中的文字