如何使用python请求刮取非restful API?

如何使用python请求刮取非restful API?,python,python-3.x,web-scraping,python-requests,data-mining,Python,Python 3.x,Web Scraping,Python Requests,Data Mining,我正在努力把这个刮干净。我从Google开发者工具的网络标签中发现,一个名为hospitals的URL请求得到了我需要的响应 我尝试在python代码中使用相同的头和负载重新创建相同的情况,但得到的响应与网站上的不同 以下是我的python代码: import requests url = r'https://tncovidbeds.tnega.org/api/hospitals' d = { "searchString":"", "sort

我正在努力把这个刮干净。我从Google开发者工具的网络标签中发现,一个名为hospitals的URL请求得到了我需要的响应

我尝试在python代码中使用相同的头和负载重新创建相同的情况,但得到的响应与网站上的不同

以下是我的python代码:

import requests

url = r'https://tncovidbeds.tnega.org/api/hospitals'

d = {
"searchString":"",
"sortCondition":{"Name":1},
"pageNumber":1,
"pageLimit":10,
"SortValue":"Availability",
"Districts":["5ea0abd3d43ec2250a483a4f"],
"BrowserId":"b4c5b065a84c7d2b60e8b23d415b2c3a",
"IsGovernmentHospital":"true",
"IsPrivateHospital":"true",
"FacilityTypes":["CHO","CHC","CCC"]
}

h = {
"authority": "tncovidbeds.tnega.org",
"method": "POST",
"path":"/api/hospitals",
"scheme": "https",
"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "en-US,en;q=0.9",
"cache-control": "no-cache",
"content-length": "280",
"content-type": "application/json;charset=UTF-8",
"cookie": "_ga=GA1.2.1066740172.1620653373; _gid=GA1.2.1460220464.1620653373",
"origin": "https://tncovidbeds.tnega.org",
"pragma": "no-cache",
"sec-ch-ua": '" Not A;Brand";v="99", "Chromium";v="90", "Google Chrome";v="90"',
"sec-ch-ua-mobile": "?0",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"token": "null",
}

res = requests.post(url, data=d, headers=h)
print(res.json())

我得到的结果是:

{
'result': None,
 'exception': '',
 'pagination': None,
 'statusCode': '500',
 'errors': [],
 'warnings': []
}
我需要的回应和谷歌网络标签上的回应是:

{
"result": A BIG LIST OF JSON OBJECTS,
"exception":null,
"pagination":{"pageNumber":1,"pageLimit":10,"skipCount":0,"totalCount":155},
"statusCode":"200",
"errors":[],
"warnings":[]}
你能给我一个解决方案吗


提前感谢。

正如我从您的浏览器请求中看到的,
内容类型必须是
应用程序/json;字符集=UTF-8
。当将有效负载作为
数据传递时
参数请求
应用程序/x-www-form-urlencoded
请求。要解决这个问题,您需要将负载作为
json
参数传递。它将自动设置正确的
内容类型

requests.post(url,json=d)

同样,在您的情况下,您不需要为请求提供任何额外的标题即可工作。

I get response Can get/hospitals update your question?如果您在浏览器中复制粘贴URL,当然您将得到一个没有响应的空白页,因为http请求必须发送到带有JSON对象的URL才能获得响应。仅仅导航到该路径不起作用。回答Gowtham Sooryaraj