python请求和beautifulsoup bot检测

标签 python html web-scraping beautifulsoup python-requests

我正在尝试使用 requests 和 beautifulsoup 抓取页面的所有 HTML 元素。我正在使用 ASIN(亚马逊标准标识号)来获取页面的产品详细信息。我的代码如下:

from urllib.request import urlopen
import requests
from bs4 import BeautifulSoup

url = "http://www.amazon.com/dp/" + 'B004CNH98C'
response = urlopen(url)
soup = BeautifulSoup(response, "html.parser")
print(soup)

但是output没有显示页面的整个 HTML,因此我无法进一步处理产品详细信息。 有什么帮助吗?

编辑 1:

根据给定的答案,它显示了机器人检测页面的标记。我研究了一下,发现了两种破坏它的方法:

  1. 我可能需要在请求中添加一个 header ,但我不明白 header 的值应该是什么。
  2. 使用 Selenium 。 现在我的问题是,这两种方式提供的支持是否相同?

最佳答案

最好在这里使用 fake_useragent 使事情变得简单。随机用户代理通过真实世界的浏览器使用统计信息发送请求。如果您不需要动态内容,几乎总是通过 HTTP 请求页面内容并以编程方式解析它会更好。

import requests
from fake_useragent import UserAgent
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
ua=UserAgent()
hdr = {'User-Agent': ua.random,
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
      'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
      'Accept-Encoding': 'none',
      'Accept-Language': 'en-US,en;q=0.8',
      'Connection': 'keep-alive'}
url = "http://www.amazon.com/dp/" + 'B004CNH98C'
response = requests.get(url, headers=hdr)
print response.content

Selenium 用于浏览器自动化和动态内容的高级网络抓取。

关于python请求和beautifulsoup bot检测,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52068920/

相关文章:

Python Pyspark : Filter for 1 Day Before Current Date Using F. current_date()

html - 是否可以在 css 样式表中嵌入字体,而不是在每个网页上定义字体?

python - 在 Selenium Python 中使用 Keys.PAGE_DOWN 滚动

python - 使用 BeautifulSoup FindAll 进行网页抓取

python - 使用 BeautifulSoup 抓取 Pantip 论坛

python - 重新索引数据帧

python - 在 python 中创建包装类时,如何让父类(super class)的方法返回包装类的实例

Python 猜谜游戏错误?

javascript - Bootstrap 时间选择器

javascript - 如何使用 jQuery 从特定/选定元素中选择第 n 个相邻元素?