python - requests 无法从某些网站检索 html 内容

标签 python web-scraping python-requests urllib3

当尝试获取网站(在本例中为 www.arrow.com)的 HTML 内容时,我什么也没得到,网络浏览器一直在等待。

import requests 

params = {'q': code}
url = "https://www.arrow.com/en/products/search"
headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',
    'cache-control': "no-cache",
    'postman-token': "564e5d76-282f-98f3-860b-d8e09e2e9073"
}
r = requests.get(url, headers=headers,params=params)
tree = html.fromstring(r.content)

奇怪的是,我可以使用 Postman 并通过网络浏览器访问来获取正确的内容。

Postman 在使用 HTTP 时使用此脚本:

GET /en/products/search?q=cccccccc HTTP/1.1
Host: www.arrow.com
Cache-Control: no-cache
Postman-Token: c3821bb3-767b-b8c7-105a-84fd16291245

或者使用Python3:

import http.client

conn = http.client.HTTPSConnection("www.arrow.com")

headers = {
    'cache-control': "no-cache",
    'postman-token': "740c5681-3e67-b605-3040-964be3ea7296"
    }

conn.request("GET", "/en/products/search?q=cccccccc", headers=headers)

res = conn.getresponse()
data = res.read()


print(data.decode("utf-8"))

使用最后一个,我也什么也没得到。

最佳答案

更改User-Agent应该可以解决这个问题,至少我在我的例子中看到了这一点。您的 params 也不正确。试试这个看看会发生什么:

import requests 
from lxml.html import fromstring

url = "https://www.arrow.com/en/products/search?"

code = "apple" #any available search terms

r = requests.get(url, 
            headers={'User-Agent': 'Mozilla/5.0'},
            params={'cat':'','q': code,'r': True}
            )
tree = fromstring(r.content)
items = tree.cssselect("h1[data-search-term]")[0].text.strip()
print(items) #it should give you the quantity of search result

关于python - requests 无法从某些网站检索 html 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53651862/

相关文章:

python - beautifulsoup4 不返回内容

javascript - Python 提交带有请求的标签

python - 具有大对象的 Memcached(NetworkX 图)

python - 将 Pandas 数据框转换为字典时,日期从字符串更改为日期时间对象

html - 如何设置连接器结果页面的样式?

javascript - 使用 VBA 插入标签值

Python 2.7 将 Hex 和 Dec 读取为 Str 然后添加它们

python - 存储 MySql 查询结果以便更快地重用

python - 使用请求从网页获取端口时遇到问题

python - Python 的 Requests 库线程中的 Session 对象是否安全?