前言
发送post的请求参考例子很简单,实际遇到的情况却是很复杂的,首先第一个post请求肯定是登录了,但登录是最难处理的。登录问题解决了,后面都简单了。
一、查看官方文档
1.学习一个新的模块,其实不用去百度什么的,直接用help函数就能查看相关注释和案例内容。
>>import requests
>>help(requests)
2.查看python发送get和post请求的案例
>>> import requests
>>> r = requests.get(‘https://www.python.org‘)
>>> r.status_code
200
>>> ‘Python is a programming language‘ in r.content
True
... or POST:
>>> payload = dict(key1=‘value1‘, key2=‘value2‘)
>>> r = requests.post(‘http://httpbin.org/post‘, data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
二、发送post请求
1.用上面给的案例,做个简单修改,发个post请求
2.payload参数是字典类型,传到如下图的form里
三、json
1.post的body是json类型,也可以用json参数传入。
2.先导入json模块,用dumps方法转化成json格式。
3.返回结果,传到data里
四、headers
1.以博客园为例,模拟登陆,实际的情况要比上面讲的几个基本内容要复杂很多,一般登陆涉及安全性方面,登陆会比较复杂
2.这里需添加请求头headers,可以用fiddler抓包
3.讲请求头写成字典格式
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
"Accept-Encoding": "gzip, deflate, br",
"Content-Type": "application/json; charset=utf-8",
"X-Requested-With": "XMLHttpRequest",
"Cookie": "xxx.............", # 此处cookie省略了
"Connection": "keep-alive"
}
五、登陆博客园
1.由于这里是https请求,直接发送请求会报错误:SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:590)
2.可以加个参数:verify=False,表示忽略对 SSL 证书的验证
3.这里请求参数payload是json格式的,用json参数传
4.红色注释那两行可以不用写
5.最后结果是json格式,可以直接用r.json返回json数据:{u‘success‘: True}
六、参考代码
# coding:utf-8
import requests
url = "https://passport.cnblogs.com/user/signin"
headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0",
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Language": "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3",
"Accept-Encoding": "gzip, deflate, br",
"Content-Type": "application/json; charset=utf-8",
# "VerificationToken": "",
"X-Requested-With": "XMLHttpRequest",
# "Referer": "",
"Content-Length": "385",
"Cookie": "xxx...", # 此处省略
"Connection": "keep-alive"
}
payload = {"input1":"xxx",
"input2":"xxx",
"remember":True}
r = requests.post(url, json=payload, headers=headers,verify=False)
print r.json()
对python接口自动化有兴趣的,可以加python接口自动化QQ群:226296743
也可以关注下我的个人公众号: