首页 > 解决方案 > AttributeError: 'NoneType' 对象没有属性 'get_text' 美丽的汤/request 并且没有输出

问题描述

import requests from bs4 import BeautifulSoup
URL = "https://www.amazon.com/HGLRC-Freestyle-Controller-Quadcopters-Multirotors/dp/B07Z1BFTVQ/ref=sr_1_5?dchild=1&keywords=freestyle+drone&qid=1605895415&sr=8-5"
headers = {"user-agent":    "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.183 Safari/537.36"}
page = requests.get(URL, headers=headers)

#----------------------------------------------------------------------------------------------------------------------------------------------------
soup = BeautifulSoup(page.content,"html.parser")

title = soup.find(id ="productTitle").get_text()
print(title.strip)

标签: pythonweb-scraping

解决方案


我测试了你的脚本,可以看到问题;您没有得到您期望的响应,因为刮擦被亚马逊阻止了

在你抓取一个网站之前,你需要检查他们的robots.txt看看你是否被允许;是 Amazon 的链接,如您所见,其中有很多Disallows

实际返回的是机器人挑战(见下文),因此代码的以下部分返回NoneType

soup.find(id ="productTitle")

最后,get_text()抛出AttributeError

在此处输入图像描述


推荐阅读