python - 无法从网页解析产品标题及其价格
问题描述
我正在尝试从网页中获取产品标题和价格,但是每次运行脚本时,我都会收到此错误``而不是内容。我检查了我在脚本中使用的选择器所在的页面源代码。
我试过:
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)
如何从上述网站获取产品名称和价格?
解决方案
将标头更改为服务器期望的标头
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)
推荐阅读
- mysql - 更新 MySQL 中 2 个表之间的电子邮件匹配 - 黑名单
- javascript - NextJS - 导出被破坏(没有 CSS,没有 JS)
- c++ - 用于透视的倒置几何 gBuffer 位置。正字法好吗?
- python - 蟒蛇 | 制作列表的百分比
- bluetooth - 与 Arduino 的 GPS 通信
- php - 无需大量代码即可将 PHP 插入代码网页设计中。解决了
- uml - 类图到序列图规则
- reactjs - 在 onClick 函数中调用更新函数时 useState 不重新渲染
- swift - ScrollView 中的 SwiftUI Picker 不正确
- python - 独立运行python包子模块进行自检;导入路径组合