请求不会从某些网站检索html内容

2024-04-24 11:48:42 发布

您现在位置:Python中文网/ 问答频道 /正文

在本例中,当尝试获取网站的HTML内容时,www.arrow.com,我什么也得不到,网络浏览器永远在等待。你知道吗

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在使用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"))

使用最后一个,我也一无所获。你知道吗


Tags: noimport网络comcache内容searchwww
1条回答
网友
1楼 · 发布于 2024-04-24 11:48:42

更改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

相关问题 更多 >