环境:python3.8.10
python使用requests的post提交数据的时候,代码写法跟抓包的headers里面的'Content-Type'有关系。
(一)记录'Content-Type': 'application/x-www-form-urlencoded'的写法。
import requests
url='https://xxx.com'
headers={
'Content-Type': 'application/x-www-form-urlencoded',
}
my_data = {'value': '{"account":"username","pwd":"pwd","type":"sign","device_info":{"model":"android","screen":"720x1280"},"extra_info":{"app_version":5000},"body":{"uid":"8899","type":1,"signin_day":1,"keep_signin":1}}'}
#简单点的就是
#my_data = {'key1':'value1'}
#或者
#my_data = {'key1':'value1','key2':'value2'}
response = requests.post(url=url, headers=headers,data=my_data)
print(response.text)
(二)记录'Content-Type': 'application/json'的写法
import requests
url='https://xxx.com'
headers={
'Content-Type': 'application/json',
}
my_data = {'value': '{"account":"username","pwd":"pwd","type":"sign","device_info":{"model":"android","screen":"720x1280"},"extra_info":{"app_version":5000},"body":{"uid":"8899","type":1,"signin_day":1,"keep_signin":1}}'}
#简单点的就是
#my_data = {'key1':'value1'}
#或者
#my_data = {'key1':'value1','key2':'value2'}
response = requests.post(url=url, headers=headers,json=my_data)
print(response.text)
以下是我编程时候的随手记:
(1)POST
#header_car中有一句 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',(表格形式)
data_car={
"ajax": "1",
"a": "confproduct",
"configure": "true",
"i": "0",
"hostname": r_name,
"rootpw": r_pwd,
"ns1prefix": "ns1",
"ns2prefix": "ns2",
"billingcycle": "monthly",
}
c_url="https://xxx.com"
#有代理
r_car=s.post(c_url,headers=header_car,proxies=proxies,data=data_car)
#无代理
r_car=s.post(c_url,headers=header_car,data=data_car)
(2)POST(涉及将字典格式转化为json数据的知识)
#如果是请求头部是'Content-Type': 'application/json'
payload = {'simpleSku': 'KS111A016-A110075000', 'anonymous': 0}#这是字典
json_data=json.dumps(payload)#将字典转变为json数据
print json_data#{"simpleSku": "KS111A016-A110075000", "anonymous": 0}这是json格式
r_car=requests.post(c_url,headers=header_car,data=json.dumps(payload))#如果请求头为'Content-Type': 'application/json',需要使用json格式的数据
print r_car.status_code
print r_car.content
还发现了一点,如果字典中有值为false,把false改为0,反而正常运行了。
或者
header_launch={
'accept': 'application/json',#说明接收的参数是json格式
'content-type': 'application/json; charset=UTF-8',
}
data_car={
"country": "CN",
"id": gdid,
"productId": productId,
"skuId": "",#空在这里代表了null
"wishlistId": wishlistId
}
url1='https://xxx.com'
result=requests.put(url1,headers=header_launch,json=data_car)#注意:headers不能缺少,json=data_car,data_car为json格式
print(result)
(3)GET
params=(
('jsv','2.4.2'),
('appKey','12574478'),
('t',millis),
('sign',sign),
('api','mtop.taobao.shop.impression.intro.get'),
('v','1.0'),
('type','originaljson'),
('secType','1'),
('timeout','3000'),
('AntiCreep','true'),
('dataType','json'),
('data',my_data),
)
result=requests.get(url_tel,headers=header_shop,params=params)
更多的内容可以参考文章:
一文详解 requests 库中 json 参数和 data 参数的用法_requests data json格式-CSDN博客
python——json、字典的区别及相互转换方法_python json转字典-CSDN博客