5
我有div標籤內的一堆div標籤:如何在美麗的湯中選擇div類內的div?
<div class="foo">
<div class="bar">I want this</div>
<div class="unwanted">Not this</div>
</div>
<div class="bar">Don't want this either
</div>
所以我使用python,美麗的湯,以獨立的東西了。只有當它被包裝在「foo」class div中時,我才需要所有「bar」類。這裏是我的代碼
from bs4 import BeautifulSoup
soup = BeautifulSoup(open(r'C:\test.htm'))
tag = soup.div
for each_div in soup.findAll('div',{'class':'foo'}):
print(tag["bar"]).encode("utf-8")
或者,我想:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open(r'C:\test.htm'))
for each_div in soup.findAll('div',{'class':'foo'}):
print(each_div.findAll('div',{'class':'bar'})).encode("utf-8")
我在做什麼錯?如果我可以從選擇中刪除div類「不需要」,我只會對簡單打印(each_div)感到滿意。