[英]Beautiful Soup remove first appearance after selector
我正在嘗試使用 Beautiful Soup 從 HTML 文本中刪除一些 HTML 。
這可能是我的 HTML 的示例:
<p>whatever</p><h2 class="myclass"><strong>fruit</strong></h2><ul><li>something</li></ul><div>whatever</div><h2 class="myclass"><strong>television</strong></h2><div>whatever</div><ul><li>test</li></ul>
關注這兩個要素:
<h2 class="myclass"><strong>television</strong></h2>
<ul>
我正在嘗試刪除<h2 class="myclass"><strong>television</strong></h2>
之后的第一個<ul>
,如果有可能我想刪除這個<ul>
只有當它出現 1或<h2>
之后的 2 個元素
那可能嗎?
您可以使用 CSS 選擇器搜索第二個<h2>
標記: h2:nth-of-type(2)
,如果之后的next_sibling
或next_sibling
是<ul>
標記,則使用.decompose()
方法:
from bs4 import BeautifulSoup
html = """<p>whatever</p><h2 class="myclass"><strong>fruit</strong></h2><ul><li>something</li></ul><div>whatever</div><h2 class="myclass"><strong>television</strong></h2><div>whatever</div><ul><li>test</li></ul>"""
soup = BeautifulSoup(html, "html.parser")
looking_for = soup.select_one("h2:nth-of-type(2)")
if (
looking_for.next_sibling.name == "ul"
or looking_for.next_sibling.next_sibling.name == "ul"
):
soup.select_one("ul:nth-of-type(2)").decompose()
print(soup.prettify())
Output:
<p>
whatever
</p>
<h2 class="myclass">
<strong>
fruit
</strong>
</h2>
<ul>
<li>
something
</li>
</ul>
<div>
whatever
</div>
<h2 class="myclass">
<strong>
television
</strong>
</h2>
<div>
whatever
</div>
您可以使用 CSS 選擇器(相鄰兄弟選擇器+
),然后.extract()
:
for tag in soup.select('h2.myclass+ul'):
tag.extract()
如果要提取所有相鄰的ul
,請使用~
選擇器:
for tag in soup.select('h2.myclass~ul'):
tag.extract()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.