Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 无法分析产品标题及其';这是网页上的价格_Python_Python 3.x_Web Scraping_Python Requests - Fatal编程技术网

Python 无法分析产品标题及其';这是网页上的价格

Python 无法分析产品标题及其';这是网页上的价格,python,python-3.x,web-scraping,python-requests,Python,Python 3.x,Web Scraping,Python Requests,我试图从网页上获取产品标题和价格,但每次运行脚本时,我都会得到这个错误,而不是内容。我签出了我在脚本中使用的选择器所在的页面源代码 我试过: 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(r

我试图从网页上获取产品标题和价格,但每次运行脚本时,我都会得到这个错误,而不是内容。我签出了我在脚本中使用的选择器所在的页面源代码

我试过:

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)

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

请尝试res.body而不是res.text


作为一种调试技术,打印请求的响应。这将帮助您使用当前配置查看从请求返回的数据。

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

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)

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

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)

是的,这很有效。但是,当我尝试使用此
https://www.amazon.com/dp/B013TCZVVS/
。引用的链接也有相同的标题。[id='priceblock\u ourprice']不适用于您的第二个url。添加用户代理的附加标题,您将在
产品名称
行看到抛出的错误。我将尝试添加更多的标题以查看其行为。请参见上面的编辑。您需要跨不同的ASIN进行检查