一、安装requests模块
1.1 适用版本
适用于python2.6、python2.7、python3.4及以上版本,参见官方说明。我这里使用的是当前最新的python3.7。
1.2 安装requests模块
1 2 3 |
pip install requests # ubuntu类系统也可以直接用apt安装 # sudo apt-get install python-requests |
二、使用requests模块完成各种操作
下边对于https的链接请求时会带上”verify=False“参数,因为默认Python会进行证书校验如果不是信任的证书会报错,带上”verify=False“指示不进行证书校验。
2.1 引用requests模块
1 |
import requests |
2.2 get请求
1 2 3 4 5 |
import requests url='https://www.baidu.com' r = requests.get(url,<span class="n">verify<span class="o">=<span class="kc">False</span></span></span>) print(r.status_code) |
2.3 post请求
1 2 3 4 5 6 |
import requests url='https://www.baidu.com' data='username=ls&password=toor' r = requests.post(url,data=data,verify=False) print(r.status_code) |
当前很多api是以json形式提交的,所以在使用post的时候我们可能想提交json数据。
提交json有两步:一是data要编码成json形式(python中的字典形式上和json一样但本质上不一样所以要编码),二是设置“Content-type”头的值为application/json(设置头部参见下面2.5,这里先用)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import json import requests # 一定要设置Content-Type值为application/json headers={} headers['Content-Type']='application/json' url='https://www.baidu.com' data={"username":"ls","password":"toor"} # 一定要用json.dumps把data格式化成json # r = requests.post(url,headers=headers,data=json.dumps(data),verify=False) # 或者直接使用json参数代替data,此时requests会自动进行格式化和设置Content-Type头的工作 r = requests.post(url,json=data,verify=False) print(r.status_code) |
为了方便对比验证,另外再附curl post提交的方法:
1 |
curl -H "Content-Type:application/json" -X POST --data '{"username": "ls","password":"toor"}' https://www.baidu.com/ |
2.4 使用代理
1 2 3 4 5 6 7 8 9 |
import requests url='http://docs.python-requests.org/en/master/' proxies={ 'http':'127.0.0.1:8080', 'https':'127.0.0.1:8080' } r = requests.get(url,proxies=proxies) print(r.status_code) |
2.5 自定义header
1 2 3 4 5 6 7 8 9 |
import requests url='http://docs.python-requests.org/en/master/' headers={ 'User-Agent':'self-defind-user-agent', 'Cookie':'name=self-define-cookies-in header' } r = requests.get(url,headers=headers) print(r.status_code) |
2.6 自定义Cookie
实验发现如果自定义header中定义了cookies那么此处设置的cookies不生效
1 2 3 4 5 6 7 |
import requests url='http://docs.python-requests.org/en/master/' cookies={'name1':'cookie1','name2':'cookies2'} #cookies=dict(name1='cookie1',name2='cookies2') r = requests.get(url,cookies=cookies) print(r.status_code) |
2.7 会话保执
经常很多请求只有在登录后才能进行,实现登录效果一般的做法是执行登录请求,然后从返回结果中提取sessionid放入自定义cookie中。
这种方法在requests中也行得通,但requests提供了更为简单的方法,直接使用request.Session类来请求即可,其保持登录的原理是保留之前请求中服务端通过set-cookie等设置的参数。
1 2 3 4 |
s = Session() url='http://docs.python-requests.org/en/master/' # 所有方法和直接使用requests时一样用即可 s.get(url) |
转载请注明:人工智能笔记 » python3使用requests模块get/post/代理/自定义header/自定义Cookie