簡體   English   中英

如何僅獲取 HTML 樹的一部分,該部分位於帶有特定字符串 BeautifulSoup 的特定標簽之上?

[英]How do I get only the part of an HTML tree which is above a certain tag with certain string BeautifulSoup?

我有一個 HTML 樹,只想要它的一部分。 即我只想要 HTML 樹的一部分,它位於帶有字符串的某個標簽之上。 該示例僅包含一個帶有Notes字符串的b標簽,但可能有多個。

<br/>
Hello
<br/>
<b>
 Notes
</b>
<br/>
Hello
<a name="test">
  Hello2
</a>

應該成為

<br/>
Hello
<br/>

使用我的代碼,我只能將所需的 output 作為列表而不是 HTML 樹。

#book.html contains the example from above
openHtml = open('book.html', 'r')
soup = BeautifulSoup(openHtml, 'html.parser')
all=soup.find_all('b')
for i in all:
    if i.text.strip() == 'Notes':
        pos = all.index(i)
soup = soup.find_all("b")[pos].find_all_previous(string=True)
print(soup)

如何獲得與 HTML 相同的結果而不是列表?

解決方案

我遍歷列表並刪除了所需標簽之后的每個元素,並從末尾刪除了標簽本身。

openHtml = open('book.html', 'r')
soup = BeautifulSoup(openHtml, 'html.parser')
all=soup.find_all('b')
for i in all:
    if i.text.strip() == 'Notes':
        pos = all.index(i)
for i in soup.find_all("b")[pos]:
    for j in i.find_all_next():
        j.extract()
soup.find_all('b')[-1].extract()
print(soup.prettify())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM