[英]How to set params in Python requests library
我在Python 2.7中使用urllib並使用以下代碼。 我正在嘗試使用請求庫執行相同的請求,但無法使其正常工作。
import urllib
import urllib2
import json
req = urllib2.Request(url='https://testone.limequery.com/index.php/admin/remotecontrol',\
data='{\"method\":\"get_session_key\",\"params\":[\"username\",\"password\"],\"id\":1}')
req.add_header('content-type', 'application/json')
req.add_header('connection', 'Keep-Alive')
f = urllib2.urlopen(req)
myretun = f.read()
j=json.loads(myretun)
print(j['result'])
使用請求庫(不起作用)
import requests
import json
d= {"method":"get_session_key","params":["username","password"],"id":"1"}
headers = {'content-type' :'application/json','connection': 'Keep-Alive'}
req2 = requests.get(url='https://testone.limequery.com/index.php/admin/remotecontrol',data=d,headers=headers)
json_data = json.loads(req2.text)
print(json data['result'])
我收到錯誤JSONDecodeError: Expecting value: line 1 column 1 (char 0)
如何使代碼與請求庫一起使用?
首先,您發送的請求類型錯誤。 你發送一個GET請求,但你需要發送一個POST,與requests.post
。
其次,將字典作為data
傳遞將對data
進行形式編碼,而不是對JSON進行編碼。 如果要在請求正文中使用JSON,請使用json
參數,而不要使用data
:
requests.post(url=..., json=d)
參考鏈接: http : //docs.python-requests.org/en/master/api/
您可以像這樣使用python的請求模塊
import requests
Req = requests.request(
method = "GET", # or "POST", "PUT", "DELETE", "PATCH" etcetera
url = "http(s)://*",
params = {"key": "value"}, # IF GET Request (Optional)
data = {"key": "value"}, # IF POST Request (Optional)
headers = {"header_name": "header_value"} # (Optional)
)
print Req.content
您可以使用try :: catch塊將代碼括起來,如下所示,以捕獲請求模塊引發的任何異常
try:
# requests.request(** Arguments)
except requests.exceptions.RequestException as e:
print e
有關完整的參數列表,請檢查參考鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.