gpt4 book ai didi

python - 使用Python(网络抓取)在BeautifulSoup上出现属性错误

转载 作者:行者123 更新时间:2023-12-01 00:23:30 25 4
gpt4 key购买 nike

我正在学习使用 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())





我正在尝试打印来自 Amazon 的某些产品的名称,但每当我尝试从 BeautifulSoup 库运行 get_text() 方法时,都会收到此错误:AttributeError: 'NoneType' 对象没有属性 'get_text'。如何才能成功打印产品名称?

最佳答案

get_text() 不起作用,因为您的选择器没有找到合适的元素,而是返回了 None。因此,您在没有 get_text() 方法的空元素上调用它。我不确定为什么 id=productTitle 不能像查看 HTML 那样工作。但是,您可以使用不同的选择器并获取其上方的 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"

关于python - 使用Python(网络抓取)在BeautifulSoup上出现属性错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58791965/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com