[英]BeautifulSoup: Get tag text up to certain tag
我想要在HTML頁面上顯示所有顯示的文本,直到命中某個標簽。 例如,我想獲取頁面上所有顯示的文本,直到找到ID為“ end_content”的標簽為止。
有辦法用BeautifulSoup做到這一點嗎? 這將與soup.get_text()方法類似,不同的是它將在擊中ID為“ end_content”的標簽后停止獲取文本。
我將執行以下操作:
html = (
'<h1>HEY!</h1>'
'<div>'
'How are'
'<h2>you?</h2>'
'<div id="end_content">END</div>'
'</div>'
'Some other text'
)
soup = BeautifulSoup(html, 'lxml')
>>> soup.select_one('#end_content').find_all_previous(string=True)[::-1]
['HEY!', 'How are', 'you?']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.