【问题标题】:BeautifulSoup .text method error: ResultSet object has no attribute 'text' [duplicate]BeautifulSoup .text 方法错误:ResultSet 对象没有属性“文本”[重复]
【发布时间】:2020-05-31 05:06:16
【问题描述】:

我创建了一个简单的刮板,但在将 ResultSet 更改为文本时遇到了问题。我想获得没有href 等的唯一文本。当我使用find 方法时效果很好,但是当我添加find_all 作为第二种方法时它显示错误:

numberone = soup.find("span", itemprop="house").text                      <---- this works good
print(numberone)

numbertwo = soup.find("div", class_="interesting").find_all('a').text     <---- this does not work
print(numbertwo)

“numberone”的输出很好,但“numbertwo”的输出显示错误:

"ResultSet 对象没有属性 '%s'。您可能正在处理一个 像单个元素一样的元素列表。你打电话 find_all() 什么时候 你是想调用 find() 吗?” % key AttributeError: ResultSet object has 没有属性“文本”。您可能正在处理一个元素列表,例如 单个元素。当你打算打电话时你打电话给 find_all() 查找()?

也许有人知道解决方案?

【问题讨论】:

  • 在错误消息中没有解决我的问题:)
  • 怎么回事?它的字面意思是您可能将元素列表视为单个元素,这还不够吗?我很困惑...
  • 就像你写的那样“可能”:)
  • 在哪种情况下您尝试...?
  • 另外,这可能是stackoverflow.com/questions/36091242/…的副本。

标签: python beautifulsoup screen-scraping


【解决方案1】:

这是因为它返回一组结果,为了打印所有结果,您可以使用这样的 for 循环:

results = numbertwo = soup.find("div", class_="interesting").find_all('a')
for result in results:
    print(result.text)

【讨论】:

  • 非常感谢,非常简单的解决方案,我会阅读的:)
  • 链接与问题有什么关系?
  • 该链接指的是 SQLAlchemy 数据库结果集,而不是 BeatifulSoup 结果集(它是列表的子类)。它们是截然不同的野兽。
  • 你是对的,我的错。我删除了链接
猜你喜欢
  • 2013-06-20
  • 2016-12-19
  • 2013-03-30
  • 1970-01-01
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多