requests-post请求
基本用法
#! /usr/bin/python3
# -*- congfig:utf-8 -*-
import requests
def test_post(url):
data = {'kw':"admin"} #请求体(字典)
headers = {"user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"} #请求头(字典)
r = requests.post(url,headers=headers,data=data) #data参数接受字典类型的请求体
#print(r.text) #中文字符无法显示
# print(r.content.decode("unicode-escape")) #unicode-escape编码,显示中文
print(r.json())
if __name__ == "__main__":
url = "https://fanyi.baidu.com/sug"
test_post(url)
{'errno': 0, 'data': [{'v': 'n. 管理; 经营;', 'k': 'admin'}, {'v': 'n. (企业、学校等的)管理,行政; 施行; 执行; (企业、学校等的)管理部门,行政部门;', 'k': 'administration'}, {'v': 'n. (公司、机构的)管理人员,行政人员;', 'k': 'administrator'}, {'v': 'adj. 管理的; 行政的;', 'k': 'administrative'}, {'v': 'v. 管理(公司、组织、机构等); 治理(国家); 施行; 执行; 给予; 提供;', 'k': 'administer'}]}
JSON格式的请求体
#! /usr/bin/python3
# -*- congfig:utf-8 -*-
import requests
def test_post(url):
data = {'username':"admin","password":"123456"}
headers = {'content-type': 'application/json'}
r = requests.post(url,headers=headers,json=data) #可以将python对象不序列化,直接传入
print(r.text)
if __name__ == "__main__":
url = "http://httpbin.org/post"
test_post(url)
{
"args": {},
"data": "{"password": "123456", "username": "admin"}",
"files": {},
"form": {},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Content-Length": "43",
"Content-Type": "application/json",
"Host": "httpbin.org",
"User-Agent": "python-requests/2.23.0",
"X-Amzn-Trace-Id": "Root=1-5f283935-ed8a46c92464f40012d9b864"
},
"json": {
"password": "123456",
"username": "admin"
},
"origin": "111.18.36.169",
"url": "http://httpbin.org/post"
}