我有一個包含多個同類元素的 html。我需要洗掉最后一個元素之后的所有內容。
html = '''
<p>Some text element.</p>
<p>Some other text element.</p>
<p class="myclass">This is an element with class</p>
<p>This is an element without class.</p>
<p>Other paragraph.</p>
<p class="myclass">The second element with class.</p>
<p>Another paragraph.</p>
<p>More</p>
<p>...</p>
'''
我設法選擇了類的最后一個元素,但我不知道如何在我的變數之后選擇所有內容。沒有找到有關洗掉正則變數的資訊。
from bs4 import BeautifulSoup
import lxml
soup = BeautifulSoup(data, 'lxml')
# Selecting all elements with class
ps_with_class = soup.find_all('p',{'class':'myclass'}
# if elements exist
if ps_with_class:
# Selecting last element
last_p_with_class = ps_with_class[-1]
# How to remove something like r"last_p_with_class*" from html? maybe using /import re/
如果我可以洗掉帶有類“myclass”的第二個元素之后的所有內容,那么輸出應該是:
<p>Some text element.</p>
<p>Some other text element.</p>
<p class="myclass">This is an element with class</p>
<p>This is an element without class.</p>
<p>Other paragraph.</p>
<p class="myclass">The second element with class.</p>
uj5u.com熱心網友回復:
你可以使用的組合.next_sibling,并extract()洗掉之后的第二匹配的所有元素<p>。
例如:
from bs4 import BeautifulSoup
import lxml
html = '''
<p>Some text element.</p>
<p>Some other text element.</p>
<p class="myclass">This is an element with class</p>
<p>This is an element without class.</p>
<p>Other paragraph.</p>
<p class="myclass">The second element with class.</p>
<p>Another paragraph.</p>
<p>More</p>
<p>...</p>
'''
soup = BeautifulSoup(html, 'lxml')
second = soup.find_all('p', {'class':'myclass'})[1]
sibling = second.next_sibling
while sibling:
next_sibling = sibling.next_sibling
sibling.extract()
sibling = next_sibling
print(soup)
這將產生一個更新的 HTML 為:
<html><body><p>Some text element.</p>
<p>Some other text element.</p>
<p class="myclass">This is an element with class</p>
<p>This is an element without class.</p>
<p>Other paragraph.</p>
<p class="myclass">The second element with class.</p></body></html>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/355576.html
