如何获取下一个标签的文本? (美丽的汤)
How to get the text of the next tag? (Beautiful Soup)
html代码是:
<div class="card border p-3">
<span class="small text-muted">Contact<br></span>
<div>Steven Cantrell</div>
<div class="small">Department of Justice</div>
<div class="small">Federal Bureau of Investigation</div>
<!---->
<!---->
<!---->
<div class="small"><a href="mailto:skcantrell@fbi.gov ">skcantrell@fbi.gov</a></div>
<div class="small">256-313-8835</div>
</div>
我想在 <div>
标签内获取输出,即 Steven Cantrell
。
我需要一种能够获取下一个标签内容的方法。在这种情况下,它是 'span',{'class':'small text-muted'}
我试过的是:
rfq_name = soup.find('span',{'class':'small text-muted'})
print(rfq_name.next)
但是这打印了 Contact
而不是名称。
您就快完成了,只需将您的印刷品更改为:print(rfq_name.find_next('div').text)
找到包含文本 "Contact"
的元素。然后使用 .find_next()
获取下一个 <div>
标签。
from bs4 import BeautifulSoup
html = '''<div class="card border p-3">
<span class="small text-muted">Contact<br></span>
<div>Steven Cantrell</div>
<div class="small">Department of Justice</div>
<div class="small">Federal Bureau of Investigation</div>
<!---->
<!---->
<!---->
<div class="small"><a href="mailto:skcantrell@fbi.gov ">skcantrell@fbi.gov</a></div>
<div class="small">256-313-8835</div>
</div>'''
soup = BeautifulSoup(html, 'html.parser')
contact = soup.find(text='Contact').find_next('div').text
输出:
print(contact)
Steven Cantrell
html代码是:
<div class="card border p-3">
<span class="small text-muted">Contact<br></span>
<div>Steven Cantrell</div>
<div class="small">Department of Justice</div>
<div class="small">Federal Bureau of Investigation</div>
<!---->
<!---->
<!---->
<div class="small"><a href="mailto:skcantrell@fbi.gov ">skcantrell@fbi.gov</a></div>
<div class="small">256-313-8835</div>
</div>
我想在 <div>
标签内获取输出,即 Steven Cantrell
。
我需要一种能够获取下一个标签内容的方法。在这种情况下,它是 'span',{'class':'small text-muted'}
我试过的是:
rfq_name = soup.find('span',{'class':'small text-muted'})
print(rfq_name.next)
但是这打印了 Contact
而不是名称。
您就快完成了,只需将您的印刷品更改为:print(rfq_name.find_next('div').text)
找到包含文本 "Contact"
的元素。然后使用 .find_next()
获取下一个 <div>
标签。
from bs4 import BeautifulSoup
html = '''<div class="card border p-3">
<span class="small text-muted">Contact<br></span>
<div>Steven Cantrell</div>
<div class="small">Department of Justice</div>
<div class="small">Federal Bureau of Investigation</div>
<!---->
<!---->
<!---->
<div class="small"><a href="mailto:skcantrell@fbi.gov ">skcantrell@fbi.gov</a></div>
<div class="small">256-313-8835</div>
</div>'''
soup = BeautifulSoup(html, 'html.parser')
contact = soup.find(text='Contact').find_next('div').text
输出:
print(contact)
Steven Cantrell