首页 > 解决方案 > 无法从网页解析产品标题及其价格

问题描述

我正在尝试从网页中获取产品标题和价格,但是每次运行脚本时,我都会收到此错误``而不是内容。我检查了我在脚本中使用的选择器所在的页面源代码。

网站链接

我试过:

import requests
from bs4 import BeautifulSoup

link = 'https://www.amazon.com/dp/B01DOLQ0BY'

res = requests.get(link,headers={"User-Agent":"Mozilla/5.0"})
soup = BeautifulSoup(res.text,"lxml")
product_name = soup.select_one("#productTitle").get_text(strip=True)
product_price = soup.select_one("[id='priceblock_ourprice']").text
print(product_name,product_price)

如何从上述网站获取产品名称和价格?

标签: pythonpython-3.xweb-scrapingpython-requests

解决方案


将标头更改为服务器期望的标头

import requests
from bs4 import BeautifulSoup

headers = {'Accept-Language': 'en-US,en;q=0.9'}

res = requests.get('https://www.amazon.com/dp/B01DOLQ0BY/', headers=headers)
soup = BeautifulSoup(res.text,"lxml")
product_name = soup.select_one("#productTitle").get_text(strip=True)
product_price = soup.select_one("[id='priceblock_ourprice']").text
print(product_name,product_price)

对于不同的产品,您需要找到一个在所有 asins 中通用的选择器。对于提供的两个,您可以使用:

import requests
from bs4 import BeautifulSoup

headers = {'Accept-Language': 'en-US,en;q=0.9','User-Agent':'Mozilla/4.0'}

asins = ['B013TCZVVS','B01DOLQ0BY']

with requests.Session() as s:
    s.headers = headers
    for asin in asins:
        res = s.get(f'https://www.amazon.com/dp/{asin}/')
        soup = BeautifulSoup(res.text,"lxml")
        product_name = soup.select_one("#productTitle").get_text(strip=True)
        product_price = soup.select_one(".comparison_baseitem_column .a-offscreen").text
        print(product_name,product_price)

推荐阅读