pythonget请求API URL返回422错误,但在浏览器上没有问题。潜在的服务人员问题?

2024-04-26 22:54:13 发布

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

我注意到,对于一些网站的API url,浏览器的返回是通过一个服务人员完成的,这导致了在获取这些API时出现问题。在

考虑以下事项:

https://www.sephora.co.id/api/v2.3/products?filter[category]=makeup/face/bronzer&page[size]=30&page[number]=1&sort=sales&include=variants,brand

当url粘贴到浏览器中时,数据会出现在中,但是当我尝试用Python中的以下代码自动收集这些数据时,会出现422错误:

import requests

#API url
url = 'https://www.sephora.co.id/api/v2.3/products?filter[category]=makeup/face/bronzer&page[size]=30&page[number]=1&sort=sales&include=variants,brand'

#The response is always 422
response = requests.get(url)

我注意到在浏览器上调用API url时,会通过服务人员返回一个响应。因此,我的问题是,有没有办法通过python请求库获得200个响应?在


Tags: httpsapiidurl人员wwwpage浏览器
1条回答
网友
1楼 · 发布于 2024-04-26 22:54:13

服务器似乎需要Accept-Language标头。
下面的代码现在返回200。在

import requests

url = 'https://www.sephora.co.id/api/v2.3/products?filter[category]=makeup/face/bronzer&page[size]=30&page[number]=1&sort=sales&include=variants,brand'

headers = {'Accept-Language': 'en-gb'}
response = requests.get(url, headers=headers)

(通过通过浏览器检查一个成功的请求,按原样将所有头添加到python请求中,然后逐个删除来确定。)

Headers from Safari webdev tools

相关问题 更多 >