Python上BeautifulSoup的属性错误(网络抓取)

我正在关注有关使用Python进行网页抓取的教程,到目前为止,我已经掌握了以下内容:

import requests
from bs4 import BeautifulSoup

URL = 'https://www.amazon.de/JBL-Charge-Bluetooth-Lautsprecher-Schwarz-      integrierter/dp/B07HGHRYCY/ref=sr_1_2_sspa?__mk_de_DE=%C3%85M%C3%85%C5%BD%C3%95%C3%91&  keywords=jbl+charge+4&qid=1562775856&s=gateway&sr=8-2-spons&psc=1'
headers = {
    "User-Agent": 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/78.0.3904.87 Mobile Safari/537.36'}
page = requests.get(URL,headers=headers)
soup = BeautifulSoup(page.text,'html.parser')
title = soup.find(id="productTitle").get_text()
print(title.strip())





我试图从亚马逊打印某些产品的名称,但是出现此错误:AttributeError:每当我尝试从BeautifulSoup库运行get_text()方法时,“ NoneType”对象都没有属性“ get_text”。如何成功打印产品名称?

congine123 回答:Python上BeautifulSoup的属性错误(网络抓取)

get_text()不起作用,因为您的选择器找不到合适的元素,而是返回了None。因此,您要在没有get_text()方法的空元素上调用它。我不确定为什么id=productTitle不能正常工作,因为它不能正常工作。但是,您可以使用其他选择器,并在其上方获得div,以获得类似的结果:

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

其输出是:

"JBL Charge 4 Bluetooth-Lautsprecher in Schwarz,Wasserfeste,portable Boombox mit integrierter Powerbank,Mit nur einer Akku-Ladung bis zu 20 Stunden kabellos Musik streamen"
,

尝试以下操作:

title = soup.find('span',id="productTitle").get_text()

这应该有效。

本文链接:https://www.f2er.com/3127945.html

大家都在问