gpt4 book ai didi

python - 使用 Python 和 BeautifulSoup 抓取 Amazon 数据时出错

转载 作者:太空宇宙 更新时间:2023-11-03 20:38:55 24 4
gpt4 key购买 nike

我刚刚开始使用 Python,我有一种奇怪的行为,Python 大部分时间都会给我一个错误,有时它会正确编译我的代码。

import requests
from bs4 import BeautifulSoup

jblCharge4URL = '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'

def get_page(url):
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
return soup

def get_product_name(url):
soup = get_page(url)
try:
title = soup.find(id="productTitle").get_text()
print("SUCCESS")
except AttributeError:
print("ERROR")
while(True)
print(get_product_name(jblCharge4URL))

控制台输出:

ERROR  
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
**SUCCESS**
None
ERROR
None
**SUCCESS**
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None
ERROR
None

提前致谢

最佳答案

我对您的代码做了一些调整,这应该会让您回到正确的轨道:

import requests
from bs4 import BeautifulSoup

jblCharge4URL = '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'

def get_page(url):
page = requests.get(url)
soup = BeautifulSoup(page.text, 'html.parser')
return soup

def get_product_name(url):
soup = get_page(url)
try:
title = soup.find(id="productTitle")
print("SUCCESS")

except AttributeError:
print("ERROR")
return(title)
print(get_product_name(jblCharge4URL))

关于python - 使用 Python 和 BeautifulSoup 抓取 Amazon 数据时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56977966/

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