【问题标题】:bs4 soup.find() returns none on Amazon pagebs4 soup.find() 在亚马逊页面上不返回任何内容
【发布时间】:2021-08-31 21:32:17
【问题描述】:

我试图在亚马逊上刮下这个产品的价格,但是当我使用 bs4 的 find 功能时,我得到一个无对象,谁能告诉我我的代码有什么问题:

from bs4 import BeautifulSoup
import smtplib
import requests
Url="https://www.amazon.fr/HyperX-Cloud-Sans-fil-interrupteur/dp/B08NTYB4M7/ref=sr_1_2?__mk_fr_FR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&crid=3O51QACXTGCAX&dchild=1&keywords=hyperx+cloud+2+wireless&qid=1630444291&sprefix=hyperx+cloud+2+w%2Caps%2C203&sr=8-2"
page=requests.get(Url)
soup=BeautifulSoup(page.content, "html.parser")
print(soup.find(id="productTitle"))

【问题讨论】:

  • 亚马逊通常会阻止 Web scappers。尝试打印page.text。你可能需要一个代理服务器来解决这个问题。
  • 你要刮价格还是产品标题?
  • 我知道 id 的价格是错误的,但是当我输入正确的 id 时,我仍然得到一个无对象

标签: python web-scraping beautifulsoup python-requests


【解决方案1】:

尝试在您的请求中添加User-Agent HTTP 标头,以便亚马逊认为您的请求来自浏览器(例如 Firefox)而不是脚本:


import requests
from bs4 import BeautifulSoup

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"
}

Url = "https://www.amazon.fr/HyperX-Cloud-Sans-fil-interrupteur/dp/B08NTYB4M7/ref=sr_1_2?__mk_fr_FR=%C3%85M%C3%85%C5%BD%C3%95%C3%91&crid=3O51QACXTGCAX&dchild=1&keywords=hyperx+cloud+2+wireless&qid=1630444291&sprefix=hyperx+cloud+2+w%2Caps%2C203&sr=8-2"
page = requests.get(Url, headers=headers)
soup = BeautifulSoup(page.content, "html.parser")
print(soup.find(id="productTitle").get_text(strip=True))

当我运行这段代码时,它会打印:

HyperX Cloud II Sans fil - Casque de jeu pour PC, PS4, interrupteur Nintendo, batterie longue durée (jusqu'à 30 heures), son Surround 7.1, microphone amovible à réduction de bruit et contrôle du micro

【讨论】:

  • 想知道我如何知道特定网站的User-Agent
  • @ezzeddin 您可以使用普通浏览器(例如 Firefox)访问该网站,然后打开开发者工具并从那里复制 User-Agent。
  • 有趣!谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多