概述
主要记录一下requests常用的一些高级特性:
1 请求和相应对象:
发送一个get请求:
取得服务器返回来的请求头:>>> r.headers
{'X-Powered-By': 'PHP 5.4.28', 'Transfer-Encoding': 'chunked', 'Set-Cookie': 'uuid=59a733d2-5eca-4c01-a669-1506642ddf54;
expires=Sun, 09-Jul-2017 14:33:49 GMT; path=/', 'Content-Encoding': 'gzip', 'Vary': 'Accept-Encoding', 'Keep-Alive': 'timeout=20',
'Server': 'openresty', 'Connection': 'keep-alive', 'Cache-Control': 'private', 'Date': 'Sat, 08 Jul 2017 14:33:50 GMT',
'Content-Type': 'text/html; charset=utf-8'}
获得我们发送的请求头:
>>> r.request.headers
{'Connection': 'keep-alive', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'User-Agent': 'python-requests/2.18.1'}
2 SSL 证书处理
主要是针对https的网站:
通过verify参数
>>> requests.get('https://github.com', verify='/path/to/certfile')
也可以忽略证书:
>>> requests.get('https://kennethreitz.org', verify=False)
<Response [200]>
3代理功能
这个功能应该是使用最多的功能之一:
import requests
proxies = {
'http': 'http://10.10.1.10:3128',
'https': 'http://10.10.1.10:1080',
}
requests.get('http://example.org', proxies=proxies)
在linux环境下也可以通过设置环境变量的方式设置代理:
$ export HTTP_PROXY="http://10.10.1.10:3128"
$ export HTTPS_PROXY="http://10.10.1.10:1080"
$ python
>>> import requests
>>> requests.get('http://example.org')
如果使用shadowsocks的vpn就需要sokcs代理:
proxies = {
'http': 'socks5://user:pass@host:port',
'https': 'socks5://user:pass@host:port'
}
最后
以上就是耍酷刺猬为你收集整理的python requests 库使用小结(二)的全部内容,希望文章能够帮你解决python requests 库使用小结(二)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复