一、请求参数类型
1.get
requests.get(url, data, cookies=cookies)
url:字符串;
data:字典类型,可以为空;
cookies:字典类型,可以为空;
无headers参数;
2.post
requests.post(url, data, headers=headers, cookies=cookies)
post请求根据编码方式有可分为:application/x-www-form-urlencoded、multipart/form-data、application/json、text/xml。
application/x-www-form-urlencoded
浏览器的原生 form 表单,如果不设置 enctype 属性,那么最终就会以 application/x-www-form-urlencoded 方式提交数据。
data:字典类型;
headers:字典类型,可以为空;
cookies:字典类型,可以为空;
url = 'http://httpbin.org/post' d = {'key1': 'value1', 'key2': 'value2'} r = requests.post(url, data=d) print r.text
application/json
data:json类型;
headers:字典类型,可以为空;
cookies:字典类型,可以为空;
url = 'http://httpbin.org/post' s = json.dumps({'key1': 'value1', 'key2': 'value2'}) r = requests.post(url, data=s) print r.text
其他参考https://www.cnblogs.com/insane-Mr-Li/p/9145152.html
3.put
requests.put(url, data, headers=headers, cookies=cookies)
与post基本一致
4.delete
requests.delete(url, headers=headers, cookies=cookies)
headers:字典类型,可以为空;
cookies:字典类型,可以为空;
无data参数;
二、数据类型转换
a='{"errno":0,"errmsg":"这是一个实例","unassigned":0,"total":0,"list":null}'
字符串转换成字典
字符串中无值为null时,可以使用eval();
字符串中是单引号时,可以使用eval();
字符串中有值为null时,可以使用json.loads();
字符串中是双引号时,可以使用json.loads();
参考https://www.cnblogs.com/lansan0701/p/9917094.html
字典转化成字符串
json.dumps();
字典中有中文时,需加 ensure_ascii=False 参数;
>>> a='{"errno":0,"errmsg":"这是一个实例","unassigned":0,"total":0,"list":null}' >>> eval(a) NameError: name 'null' is not defined >>> import json >>> json.loads(a) {'total': 0, 'errno': 0, 'errmsg': '这是一个实例', 'unassigned': 0, 'list': None} >>> json.dumps(a) '"{\\"errno\\":0,\\"errmsg\\":\\"\\u8fd9\\u662f\\u4e00\\u4e2a\\u5b9e\\u4f8b\\",\\"unassigned\\":0,\\"total\\":0,\\"list\\":null}"' >>> json.dumps(a, ensure_ascii=False) '"{\\"errno\\":0,\\"errmsg\\":\\"这是一个实例\\",\\"unassigned\\":0,\\"total\\":0,\\"list\\":null}"'
三、获取cookies
res = requests.post('http://www.xxx.com', {'username':'lilei', 'password'='123456'})
cookies = res.cookies #此处类型为<class 'requests.cookies.RequestsCookieJar'>
cookies = requests.utils.dict_from_cookiejar(cookies) #将CookieJar转为字典