![](/img/trans.png)
[英]Extract text only except the content of script tag from html with BeautifulSoup
[英]Extract text in BeautifulSoup except for one tag
我正在嘗試使用BeautifulSoup提取文本。
這是html:
<div>
"BLABLA"
<span> "RRRRR" </span>
<span> "ZZZZZ" </span>
</div>
我只想獲得'BLABLA'
和'RRRR'
並獲得'ZZZZ'
當然soup.text
。文本給了我這三個文本。
一種解決方案是進行迭代,直到找到第二個跨度為止(如這個問題: 如何使用BeautifulSoup在兩個指定標簽之間獲取所有文本? )
但是在這種情況下有更好的解決方案嗎?
您可以使用以下代碼(可以根據需要進行修改):
from bs4 import BeautifulSoup, NavigableString
html = '''
<div>
"BLABLA"
<span> "RRRRR" </span>
<span> "ZZZZZ" </span>
</div>'''
soup = BeautifulSoup(html, 'lxml')
wanted_text = [x.strip() if isinstance(x, NavigableString) else x.text.strip() for x in soup.find('div').contents[:2]]
print(wanted_text)
# ['"BLABLA"', '"RRRRR"']
如果HTML稍有變化,則只需更改切片索引(即,將contents[:2]
更改為所需的contents[:2]
)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.