我在使用 BeautifulSoup 收集特定标签的信息时遇到问题。我想提取 html 标签之间的“Item 4”文本,但下面的代码获取与“Item 1”相关的文本。我做错了什么(例如切片)?
代码:
primary_detail = page_section.findAll('div', {'class': 'detail-item'})
for item_4 in page_section.find('h3', string='Item 4'):
if item_4:
for item_4_content in page_section.find('html'):
print (item_4_content)
HTML:
<div class="detail-item">
<h3>Item 1</h3>
<html><body><p>Item 1 text here</p></body></html>
</div>
<div class="detail-item">
<h3>Item 2</h3>
<html><body><p>Item 2 text here</p></body></html>
</div>
<div class="detail-item">
<h3>Item 3</h3>
<html><body><p>Item 3 text here</p></body></html>
</div>
<div class="detail-item">
<h3>Item 4</h3>
<html><body><p>Item 4 text here</p></body></html>
</div>
最佳答案
您似乎想打印 <p>
标签内容根据<h3>
文本值,正确吗?
您的代码必须:
- 加载
html_source
- 搜索全部
'div'
包含'class'
的标签等于'detail-item'
- 对于每次出现,如果
.text
<h3>
的值标签等于字符串'Item 4'
- 那么代码将
print
.text
对应<p>
的值标签
您可以使用以下代码来实现您想要的目的。
代码:
s = '''<div class="detail-item">
<h3>Item 1</h3>
<html><body><p>Item 1 text here</p></body></html>
</div>
<div class="detail-item">
<h3>Item 2</h3>
<html><body><p>Item 2 text here</p></body></html>
</div>
<div class="detail-item">
<h3>Item 3</h3>
<html><body><p>Item 3 text here</p></body></html>
</div>
<div class="detail-item">
<h3>Item 4</h3>
<html><body><p>Item 4 text here</p></body></html>
</div>'''
from bs4 import BeautifulSoup
soup = BeautifulSoup(s, 'lxml')
primary_detail = soup.find_all('div', {'class': 'detail-item'})
for tag in primary_detail:
if 'Item 4' in tag.h3.text:
print(tag.p.text)
输出:
'Item 4 text here'
编辑:在provided website中第一次循环发生时没有 <h3>
标签,只有一个<h2>
所以它不会有任何 .text
值,正确吗?
您可以使用 try/except
绕过此错误子句,如以下代码所示..
代码:
from bs4 import BeautifulSoup
import requests
url = 'https://fortiguard.com/psirt/FG-IR-17-097'
html_source = requests.get(url).text
soup = BeautifulSoup(html_source, 'lxml')
primary_detail = soup.find_all('div', {'class': 'detail-item'})
for tag in primary_detail:
try:
if 'Solutions' in tag.h3.text:
print(tag.p.text)
except:
continue
如果代码遇到异常,它将继续迭代循环中的下一个元素。因此代码将忽略不包含任何 .text
的第一项值。
输出:
'Upgrade to FortiWLC-SD version 8.3.0'
关于python - BeautifulSoup 不提取特定标签文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43593468/