我试图从网页上获取产品标题及其价格,但是每次运行脚本时,都会出现此错误''而不是内容。我签出了页面源,在脚本中使用的选择器在那里。
我尝试过:
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)
如何从上述站点获取产品名称及其价格?
答案 0 :(得分:1)
将标头更改为服务器期望的标头
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)
答案 1 :(得分:0)
尝试使用res.body代替res.text
作为一种调试技术,也可以打印请求的响应。这样可以帮助您查看使用当前配置从请求返回的数据。