python requests 库使用小结(二)

主要记录一下requests常用的一些高级特性:

1 请求和相应对象:

发送一个get请求:

r = requests.get('http://blog.csdn.net/hanglinux')
取得服务器返回来的请求头:

>>> 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'
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值