python - BeautifulSoup 不提取特定标签文本

标签 python web-scraping beautifulsoup

我在使用 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>文本值,正确吗?

您的代码必须:

  1. 加载html_source
  2. 搜索全部 'div'包含 'class' 的标签等于 'detail-item'
  3. 对于每次出现,如果 .text <h3> 的值标签等于字符串 'Item 4'
  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/

相关文章:

Python:无法在我的代码中找到错误。 os.walk() 返回的文件名

python - BS 无法在 Selenium 检索页面中获取部分 id

python - 忘记一些东西 - Python BeautifulSoup 和 FinViz

python - 如何使用lxml(或BeautifulSoup)提取两个跨度之间的文本?

python - 交互式列表框 Tkinter

python - 根据一些特定的列合并数据,pandas

python - 用方法补丁(装饰器)覆盖类补丁

python - 无法使用包含空格和连字符的类名使用scrapy提取数据

PHPQuery WebBrowser 插件 - 使用 cookie

python - 从 HTML 文件顶部抓取 'dictionary' 类型对象(一堆文本,不在类中)