【问题标题】:BeautifulSoup AttributeError: 'NoneType' object has no attribute 'text'BeautifulSoup AttributeError:“NoneType”对象没有属性“文本”
【发布时间】:2019-12-24 10:41:04
【问题描述】:

我正在尝试学习如何抓取网站,因此不使用 API。我正在尝试抓取 eBay 的网站,我的脚本运行了几分钟,但由于错误提示“AttributeError: 'NoneType' object has no attribute 'text'”而停止。我做了尽职调查并在 Google/StackOverflow 帮助上进行了搜索,但找不到任何帮助。错误指向下面的代码,但我不知道如何修复它。

total_sold_price = soup.find('span', {'class': 'vi-qtyS-hot-red'}).text

if total_sold_price:
    total_sold_price = soup.find('span', {'class': 'vi-qtyS-hot-red'}).text

else:
    try:
        total_sold_price = soup.find('a', {'class': 'vi-txt-underline'}).text
    except Exception as e:
        print(e)
        total_sold_price = ""

完整代码:https://pastebin.com/xS4bAwZK

提前致谢,非常感谢。

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    问题是soup.find('span', {'class': 'vi-qtyS-hot-red'}) 返回无,然后您尝试提取文本.text 无(因此出现错误消息)。有几种方法可以处理它。我所做的只是绕开一些逻辑:

    另外,你让它存储文本total_sold_price = soup.find('span', {'class': 'vi-qtyS-hot-red'}).text,如果它存储它,你让它做一些多余的事情。

    最后,页面是动态的,因此您可能需要研究 API 或其他方式来访问数据。

    但是对于您提供的代码,可能是这样的:

    try:
        total_sold_price = soup.find('span', {'class': 'vi-qtyS-hot-red'}).text
    except Exception as e:
        try:
            total_sold_price = soup.find('a', {'class': 'vi-txt-underline'}).text
        except Exception as e:
                    print(e)
                    total_sold_price = ""
    

    【讨论】:

      【解决方案2】:

      解决了吗? 而不是 {'class': 'vi-qtyS-hot-red'} 你可以写='vi-qtyS-hot-red'

      不需要写'class'和{}

      【讨论】:

      • 你不能,因为你会指定它是一个类还是一个标识符,然后输入它的地址以便从中获取数据
      • 欢迎来到 Stack Overflow!请花点时间阅读editing help 中的help center。 Stack Overflow 上的格式与其他网站不同。
      猜你喜欢
      • 1970-01-01
      • 2018-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2019-04-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多