py不要调和“ .content”,“ get_text”和“ .strip()”并且我安装bs4

时间:2019-08-13 01:10:20

标签: python beautifulsoup

我安装了bs4,并遵循了一些有关Web抓取的教程。我写了一些代码,但问题是python无法识别.contentget_text.strip()

import requests

from bs4 import BeautifulSoup 

URL = 'https://www.amazon.com/HP-Pavilion-21-5-Inch-Monitor-22cwa/dp/B015WCV70W/ref=sr_1_4?keywords=screen+hp&qid=1565652560&s=gateway&sr=8-4'

headers = {"user agent": 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 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())

这些是消息:

Traceback (most recent call last):
  File "d:/Desktop/python/Webscraper/scrapter.py", line 12, in <module>
    title = soup.find(id="productTitle").get_text()
AttributeError: 'NoneType' object has no attribute 'get_text'

Traceback (most recent call last):
  File "d:/Desktop/python/Webscraper/scrapter.py", line 13, in <module>
    print(title.strip())
AttributeError: 'NoneType' object has no attribute 'strip'

2 个答案:

答案 0 :(得分:0)

抓取他们的网站违反了亚马逊的terms and conditions

但是,还有另一种方法。您可以做的就是向他们here注册为开发人员以使用其api。

答案 1 :(得分:0)

要回答您的问题,您会遇到这些错误,因为找不到元素。当您使用漂亮的汤法搜索某些东西时,找不到匹配项; None返回。