我正試圖從2012年奧巴馬 - 羅姆尼總統的辯論中摘錄報價。問題是the site組織不良。因此,結構是這樣的:如何使用BeautifulSoup根據孩子和兄弟姐妹選擇標籤?
<span class="displaytext">
<p>
<i>OBAMA</i>Obama's first quotes
</p>
<p>More quotes from Obama</p>
<p>Some more Obama quotes</p>
<p>
<i>Moderator</i>Moderator's quotes
</p>
<p>Some more quotes</p>
<p>
<i>ROMNEY</i>Romney's quotes
</p>
<p>More quotes from Romney</p>
<p>Some more Romney quotes</p>
</span>
有沒有一種方法來選擇<p>
,其第一個孩子是一個i
具有文本OBAMA
和所有它的p
兄弟姐妹,直到你遇到下一個p
他們的第一個孩子是一個i
沒有文字Obama
??
這裏是我試過到目前爲止,但它僅抓住了第一個p
無視兄弟姐妹
input = '''<span class="displaytext">
<p>
<i>OBAMA</i>Obama's first quotes
</p>
<p>More quotes from Obama</p>
<p>Some more Obama quotes</p>
<p>
<i>Moderator</i>Moderator's quotes
</p>
<p>Some more quotes</p>
<p>
<i>ROMNEY</i>Romney's quotes
</p>
<p>More quotes from Romney</p>
<p>Some more Romney quotes</p>
</span>'''
soup = BeautifulSoup(input)
debate_text = soup.find("span", { "class" : "displaytext" })
president_quotes = debate_text.find_all("i", text="OBAMA")
for i in president_quotes:
siblings = i.next_siblings
for sibling in siblings:
print(sibling)
其中僅打印Obama's first quotes