【问题标题】:python beautifulsoup4 how to get span text in div tagpython beautifulsoup4如何在div标签中获取跨度文本
【发布时间】:2021-10-27 07:58:43
【问题描述】:

这是html代码

<div aria-label="RM 6,000 a month" class="salary-snippet"><span>RM 6,000 a month</span></div>

我是这样用的

divs = soup.find_all('div', class_='job_seen_beacon')
    for item in divs:
        print(item.find('div', class_='salary-snippet'))

我得到了一个列表,例如

<div aria-label="RM 3,500 to RM 8,000 a month" class="salary-snippet"><span>RM 3,500 - RM 8,000 a month</span></div>

如果我用过

print(item.find('div', class_='salary-snippet').text.strip())

它会返回错误

AttributeError: 'NoneType' object has no attribute 'text'

那么我怎样才能只获得跨度文本?这是我第一次网络抓取

【问题讨论】:

  • 请发布您的完整代码,包括网址,以便我们重现问题

标签: python python-3.x web-scraping beautifulsoup


【解决方案1】:

也许这就是你要找的东西。

  • 首先选择类为salary-snippet 的所有&lt;div&gt; 标签,因为这是您要查找的&lt;span&gt; 标签的父标签。使用.find_all()
  • 现在从上面遍历所有选定的&lt;div&gt; 标签,并从每个&lt;div&gt; 中找到&lt;span&gt;
  • 根据您的问题,我假设所有这些&lt;div&gt; 可能没有&lt;span&gt; 标记。在这种情况下,只有当&lt;div&gt; 包含span 标记时,您才能打印文本。见下文
# Find all the divs
d = soup.find_all('div', class_='salary-snippet')
# Iterating over the <div> tags
for item in d:
    # Find <span> in each item. If not exists x will be None
    x = item.find('span')
    # Check if x is not None and then only print
    if x:
        print(x.text.strip())

这是完整的代码。

from bs4 import BeautifulSoup

s = """<div aria-label="RM 6,000 a month" class="salary-snippet"><span>RM 6,000 a month</span></div>"""
soup = BeautifulSoup(s, 'lxml')

d = soup.find_all('div', class_='salary-snippet')
for item in d:
    x = item.find('span')
    if x:
        print(x.text.strip())
RM 6,000 a month

【讨论】:

  • 谢谢,我从没想过使用 find_all 会起作用...我猜即使它只有一个跨度文本,迭代以获得跨度文本仍然可以发挥作用
【解决方案2】:

我认为这行应该是:

print(item.find('div', {'class':'salary-snippet'}).text.strip())

或者,如果只有span,您可以简单地使用:

item.find("span").text.strip()

考虑到您使用了.find_all() 方法,您可能希望确保每个div 从您的HTML 返回

soup.find_all('div', class_='job_seen_beacon')

包含您要查找的元素,因为如果只有一个元素不包含,则可能会出现 thi。

divs = soup.find_all('div', class_='job_seen_beacon')
for item in divs:
    try:
        print(item.find('div', {'class':'salary-snippet'}).text.strip())
    except AttributeError:
        print("Item Not available")

这将尝试获取文本,但如果失败将打印失败的项目,以便您确定原因......也许它没有您正在搜索的元素。

【讨论】:

  • 感谢您的编辑,但我也会为他/她打印该项目,以确定为什么它没有该属性,但这只是个人调试偏好
猜你喜欢
  • 2019-11-01
  • 2014-09-23
  • 1970-01-01
  • 1970-01-01
  • 2016-04-01
  • 1970-01-01
  • 2019-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多