[英]Taking specific text from a div in python3
這是我試圖從中提取的 html 示例:
<div class="small subtle link">
<a href="https://example.com" target="_blank" nofollow >Example</a>
This text!
</div>
我想抓住“這個文本!” 但是當我這樣做時,我不斷得到“示例”
myText=soup.findAll('div',{'class':re.compile('small subtle link')})
if myText:
extractedText=myText.text.strip()
如何省略 a 標簽中的文本?
有幾種可能的解決方案,這一切都取決於您正在尋找的確切行為。
這會產生正確的輸出:
from bs4 import BeautifulSoup
html_src = \
'''
<html>
<body>
<div class="small subtle link">
<a href="https://example.com" nofollow="" target='"_blank"'>
Example
</a>
This text!
</div>
</body>
</html>
'''
soup = BeautifulSoup(html_src, 'lxml')
print(soup.prettify())
div_tag = soup.find(name='div', attrs={'class': 'small subtle link'})
div_content_text = []
for curr_text in div_tag.find_all(recursive=False, text=True):
curr_text = curr_text.strip()
if curr_text:
div_content_text.append(curr_text)
print(div_content_text)
這是你需要的:
soup.div.find(text=True, recursive=False)
你可以試試這個:
print(div.a.find_next_sibling(text=True).strip())
這會在div
下找到a
標簽並打印它后面的文本。
這是完整的代碼:
from bs4 import BeautifulSoup
html = """
<div class="small subtle link">
<a href="https://example.com" target="_blank" nofollow >Example</a>
This text!
</div>
"""
soup = BeautifulSoup(html,'html5lib')
div = soup.find('div', class_ = "small subtle link")
print(div.a.find_next_sibling(text=True).strip())
輸出:
This text!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.