【问题标题】:BeautifulSoup 'find()' returns NoneType ValueBeautifulSoup 'find()' 返回 NoneType 值
【发布时间】:2020-10-18 15:19:39
【问题描述】:

我刚刚开始尝试使用 Python 编写价格跟踪器,并且已经遇到了一个我不明白的错误。这是代码:

from bs4 import BeautifulSoup

URL = 'https://www.amazon.com/Corsair-Platinum-Mechanical-Keyboard-Backlit/dp/B082GR814B/'
HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0."
                         "4103.116 Safari/537.36"}
targetPrice = 150


def getPrice():
    page = requests.get(URL, headers=HEADERS)
    soup = BeautifulSoup(page.content, 'html.parser')
    price = soup.find(id="priceblock_ourprice").get_text()    # Error happens here
    print(price)


if True:
    getPrice()

我看到这部分soup.find(id="priceblock_ourprice") 返回值'None',因此出现AttributeError。我不明白为什么它返回“无”值。只有一次代码真正起作用并打印了产品价格,然后再也没有。我在一次成功尝试后再次运行脚本而没有更改任何内容,并再次一致地得到 AttributeError。

我还尝试了以下方法:

使用 html5lib 和 lxml 代替 html.parser。 不同的 id,看看我是否可以访问网站的不同部分。 其他用户代理。 我还从 github 下载了一个类似的程序,它使用完全相同的代码来查看它是否会运行,但它也没有。

这里发生了什么?任何帮助将不胜感激。

【问题讨论】:

    标签: python web-scraping beautifulsoup attributeerror nonetype


    【解决方案1】:

    您正在获取验证码页面。尝试在浏览器中设置更多 HTTP 标头以获得正确的页面。当我设置 Accept-Language http 标头时,我无法再重现错误:

    import requests
    from bs4 import BeautifulSoup
    
    
    URL = 'https://www.amazon.com/Corsair-Platinum-Mechanical-Keyboard-Backlit/dp/B082GR814B/'
    HEADERS = {
        "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:77.0) Gecko/20100101 Firefox/77.0",
        'Accept-Language': 'en-US,en;q=0.5',
    }
    
    def getPrice():
        page = requests.get(URL, headers=HEADERS)
        soup = BeautifulSoup(page.content, 'html.parser')
        price = soup.find(id="priceblock_ourprice").get_text()
        print(price)
    
    
    getPrice()
    

    打印:

    $195.99
    

    【讨论】:

    • 谢谢你,我真的很感激。那么,亚马逊“实际上不允许”抓取?
    • @WilmerKluever 最好阅读他们的服务条款。我想他们有一些官方 API 可以得到这样的结果。
    • 谢谢。我对 HTML 不太了解。我将如何从这里提取文本? R 1,739 我住在南非,所以我使用其他在线商店。因此兰特货币
    • @WilmerKluever 我会使用soup.select_one('span.currency').text,但我建议打开一个新问题。每个网站/网店都有点具体。
    【解决方案2】:

    尝试在soup = BeautifulSoup(page.content, 'html.parser') 之后打印soup

    亚马逊知道您正在尝试抓取它们,因此您认为它们返回的页面并非如此。

    Getting blocked when scraping Amazon (even with headers, proxies, delay)

    【讨论】:

      猜你喜欢
      • 2016-02-19
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 1970-01-01
      • 2017-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多