【发布时间】: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