【问题标题】:AttributeError: 'ResultSet' object has no attribute 'find_all' [closed]AttributeError:“ResultSet”对象没有属性“find_all”[关闭]
【发布时间】:2016-08-16 05:42:04
【问题描述】:

哪里出错了?我想解析没有标签的文本。

from bs4 import BeautifulSoup       
import re
import urllib.request
f = urllib.request.urlopen("http://www.championat.com/football/news-2442480-orlov-zenit-obespokoen---pole-na-novom-stadione-mozhet-byt-nekachestvennym.html")

soup = BeautifulSoup(f, 'html.parser')

soup=soup.find_all('div', class_="text-decor article__contain")

invalid_tags = ['b', 'i', 'u', 'br', 'a']

for tag in invalid_tags: 

  for match in soup.find_all(tag):

        match.replaceWithChildren()

soup = ''.join(map(str, soup.contents))

print (soup)

错误:

Traceback (most recent call last):
  File "1.py", line 9, in <module>
    for match in soup.find_all(tag):
AttributeError: 'ResultSet' object has no attribute 'find_all'

【问题讨论】:

  • 您将 soup 替换为结果集:soup=soup.find_all('div', class_="text-decor article__contain")。结果集只是一个列表,其中包含对原始汤对象的额外引用。我不清楚为什么要用结果集替换 BeautifulSoup 对象,如果您想进行嵌套搜索,请改用 CSS selector
  • 你真的很想看output formatting,不要将对象映射到字符串。

标签: python beautifulsoup resultset findall


【解决方案1】:

soup=soup.find_all('div', class_="text-decor article__contain")

在这一行,soup 变成了一个 ResultSet 实例 - 基本上是一个 Tag 实例的列表。而且,您将获得'ResultSet' object has no attribute 'find_all',因为此ResultSet 实例没有find_all() 方法。仅供参考,这个问题实际上在文档中的troubleshooting section 中有所描述:

AttributeError: 'ResultSet' object has no attribute 'foo' - 这个 通常发生是因为您希望 find_all() 返回单个标签 或字符串。但是find_all() 返回标签和字符串的list——a 结果集对象。您需要遍历列表并查看 .foo 的每一个。或者,如果你真的只想要一个结果,你需要 使用find() 而不是find_all()

你真的想要一个结果,因为页面上有一篇文章:

soup = soup.find('div', class_="text-decor article__contain")

请注意,虽然不需要逐个查找标签,但您可以将标签名称列表直接传递给find_all() - BeautifulSoup 在定位元素方面非常灵活:

article = soup.find('div', class_="text-decor article__contain")

invalid_tags = ['b', 'i', 'u', 'br', 'a']
for match in article.find_all(invalid_tags):
     match.unwrap()  # bs4 alternative for replaceWithChildren

【讨论】:

    猜你喜欢
    • 2017-04-25
    • 1970-01-01
    • 2018-08-06
    • 1970-01-01
    • 2016-12-19
    • 2013-03-30
    • 1970-01-01
    • 2014-10-23
    • 2020-03-11
    相关资源
    最近更新 更多