使用Python和BeautifulSoup获取Amazon数据时出错

2024-10-01 04:49:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始使用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))

控制台输出:

^{pr2}$

提前谢谢


Tags: nameimporturlgetdefpagedeproduct
3条回答

除了使用requestsBeautifulSoup组合之外,还可以使用requests-html包来下载网页并同时解析内容。使用请求html的示例如下:

from requests_html import HTMLSession

url = r"https://www.amazon.de/JBL-Charge-Bluetooth-Lautsprecher-Schwarz-integrierter/dp/B07HGHRYCY/"

req = HTMLSession().get(url)
product_title = req.html.find("#productTitle", first=True)
print(product_title.text)  #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

希望有帮助。在

您在page = requests.get(url, headers=headers)中使用什么headers? 你可能需要一些东西,诱使服务器相信你是一个真正的用户,而不是一个脚本。我建议你用一些基本的东西

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'}

另外,在调试此问题时,您可能希望在异常中打印变量soup的值。打印soup将为您提供页面的HTML,然后您可以深入源代码以了解问题所在。在

我对您的代码做了一些调整,这将使您回到正确的轨道:

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))

相关问题 更多 >