使用python返回400发送Ajax请求

2024-10-01 05:02:12 发布

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

我试图发送ajax请求并获取json数据,但是我收到了400个错误的请求

我试过传递不同的标题,但还是不行

import requests
import json

headers = {"Host": "www.zalando-prive.it",
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",
           "Accept": "application/json, text/plain, */*",
           "Accept-Language": "en-US",
           "Accept-Encoding": "gzip, deflate, br",
           "X-Requested-With": "XMLHttpRequest",
           "Referer":"https: //www.zalando-prive.it/campaigns/ZZLPH1"
}

data = {"filter": {},
        "sort": "attractivity",
        "gender": "FEMALE",
        "page": 1}

url = "https://www.zalando-prive.it/api/campaigns/ZZLPH1/articles"
response = requests.get(url, data=data, headers=headers)
print(response.text)

您的浏览器发送了一个服务器无法理解的请求,而我期望json响应


Tags: texthttpsimportjsonurldatawwwit
1条回答
网友
1楼 · 发布于 2024-10-01 05:02:12

如果你能提供更多的信息,我只能猜出你想做什么。在

您可以按照注释中的建议将data=data更改为params=data。但是,这将以html形式给出响应,而不是json响应(同样,如果您提供了更多信息,我们可以调试该问题)。在

在html源代码中,有一个json响应,但是需要通过一些字符串操作将其提取出来,然后进行解码。完成后,使用json.loads()来获得:

import requests
import json
from urllib.parse import unquote

headers = {"Host": "www.zalando-prive.it",
           "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:67.0) Gecko/20100101 Firefox/67.0",
           "Accept": "application/json, text/plain, */*",
           "Accept-Language": "en-US",
           "Accept-Encoding": "gzip, deflate, br",
           "X-Requested-With": "XMLHttpRequest",
           "Referer":"https://www.zalando-prive.it/campaigns/ZZLPH1"
}

data = {"filter": {},
        "sort": "attractivity",
        "gender": "FEMALE",
        "page": 1}

url = "https://www.zalando-prive.it/api/campaigns/ZZLPH1/articles"
response = requests.get(url, params=data, headers=headers)
print(response.text)

jsonStr = response.text
jsonStr = jsonStr.split('data-cms-content="')[-1]
jsonStr = jsonStr.split('" data-reactroot="">')[0]

jsonData = json.loads(unquote(jsonStr))

相关问题 更多 >