【问题标题】:Beautiful Soup code returning an "AttributeError"漂亮的汤代码返回“AttributeError”
【发布时间】:2020-07-11 12:14:18
【问题描述】:

我正在构建一个 webscraper,它返回写在网站上的咖啡馆名称,如下所示:<h2 class="venue-title" itemprop="name">Prior</h2> 但是它返回了这个错误:

“ResultSet 对象没有属性 '%s'。您可能将元素列表视为单个元素。当您打算调用 find() 时是否调用了 find_all()?” % 钥匙 AttributeError:ResultSet 对象没有属性“文本”。您可能将元素列表视为单个元素。当您打算调用 find() 时,您是否调用了 find_all()? [0.699s完成]

代码如下:

from bs4 import BeautifulSoup
import requests

url = 'https://www.broadsheet.com.au/melbourne/guides/best-cafes-thornbury'
response = requests.get(url, timeout=5)

soup_cafe_list = BeautifulSoup(response.content, "html.parser")
type(soup_cafe_list)

cafes = soup_cafe_list.findAll('h2', attrs_={"class":"venue-title"}).text
print(cafes)

我已经尝试了很多方法来解决这个问题。我觉得它与 findAll 参数有关:cafes = soup_cafe_list.findAll('h2', attrs_={"class":"venue-title"}).text 因为当我以cafes = soup_cafe_list.findAll('h2', class_="venue-title") 运行它时,它的工作期望不会返回我认为.text 应该做的从其html 中清除的项目?

我在回溯中注意到的另一件事是它可能指的是 BS4 的不同目录?这与它有什么关系吗?我开始使用 Jupyter,现在在 Atom 上,但可能错误地安装了 bs4:

文件“/Users/[xxxxxxxx]/Desktop/Coding/amvpscraper/webscraper.py”,第 10 行,在 cafes = soup_cafe_list.findAll('h2', attrs_={"class":"venue-title"}).text getattr

中的文件“/Users/[xxxxxxxx]/opt/anaconda3/lib/python3.7/site-packages/bs4/element.py”,第 2081 行

不确定我是否做错了什么......

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    错误表示findAll方法的返回值是一个元素列表,没有text属性。将结果保存在列表中(不带 .text 方法)并将 attrs_ 替换为 attrs:

    cafes = soup_cafe_list.findAll('h2', attrs={"class":"venue-title"})
    

    然后遍历列表并获取文本。您可以通过列表理解来做到这一点:

    cafes = [el.text for el in cafes]
    

    编辑:列表推导式简化了 for 循环。你也可以写:

    res_list = []
    for el in cafes:
        res_list.append(el.text)
    

    此外,您可以添加一些 try-except 子句或检查循环内的有效文本字段以捕获可能没有文本的元素。

    输出:

    ['Prior',
     'Rat the Cafe',
     'Ampersand Coffee and Food',
     'Umberto Espresso Bar',
     'Brother Alec',
     'Short Round',
     'Jerry Joy',
     'The Old Milk Bar',
     'Little Henri',
     'Northern Soul']
    

    【讨论】:

    • 感谢您的回复,我现在运行代码时似乎只是返回 [ ]?
    • 你确定吗?我得到这个列表:['Prior','Rat the Cafe','Ampersand Coffee and Food','Umberto Espresso Bar','Brother Alec','Short Round','Jerry Joy','The Old Milk Bar' , 'Little Henri', 'Northern Soul'] 编辑:我在您的代码中重命名了 attrs_ 关键字。这必须是 attrs
    • 太棒了,成功了。谢谢你。只是出于兴趣,您能解释一下第二行代码cafes = [el.text for el in cafes] 的工作原理吗?
    • @deadant88 将此添加到答案中。它被称为列表推导并简化了 for 循环。
    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 1970-01-01
    • 2023-02-04
    • 2015-11-19
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多