pythonrequests示例_Python Requests库基本用法示例

本文实例讲述了python requests库基本用法。分享给大家供大家参考,具体如下:

requests是python的一个http client库,提供了一套简捷的api供开发者使用。下面简单介绍一下其安装和使用。这里是官方文档。

0 安装

pip install requests

1 发送请求

r=requests.get('https://www.baidu.com')

print r.status_code,r.text

r=requests.post('http://httpbin.org/post')

r=requests.put('http://httpbin.org/put')

r=requests.delete('http://httpbin.org/delete')

r=requests.head('http://httpbin.org/head')

r=requests.options('http://httpbin.org/')

2 发送get参数

param={'key1':value1,'key2':value2}

r=requests.get('http://www.baidu.com/',params=param)

3 发送post参数

param={'key1':value1,'key2':value2}

r=requests.post('http://www.baidu.com/',params=param) #表单格式

r=requests.post('http://www.baidu.com/',json=param) #json格式数据

file= {'file':open('1.txt','rb')}

r=reuqest.post('http://httpbin.org/post',files=file)

4 文件下载

with open('1.pic','wb') as pic:

for chunk in response.iter_content(size):

pic.write(chunk)

5 携带header

header={'key1':value1,'key2':value2}

r=requests.get('http://www.baidu.com/',headers=header)

6 携带cookie

cookie={'key1':value1,'key2':value2}

r=requests.get('http://www.baidu.com/',cookies=cookie)

7 重定向

默认requests是允许重定向的,并将重定向的历史保存在response.history数组中

如果不需要重定向,可以通过开关来关闭

r=requests.get('http://www.baidu.com/',allow_redirects=false)

8 使用代理

使用socks代理需要安装三方扩展包

pip install requests[socks]

proxy={

'http':'http://127.0.0.1:8000',

'https':'https://127.0.0.1:8080'

'http':'socks5://user:pass@127.0.0.1:8132'

}

r=requests.get('https://www.github.com/',proxies=proxy)

9 设置连接超时

r=requests.get('http://www.baidu.com/',timeout=2.5)

10 ssl证书

证书验证

requests.get('https://kennethreitz.com', verify=true)

requests.get('https://kennethreitz.com', cert=('/path/server.crt', '/path/key'))

如果指定本地证书及密钥,则密钥需要是解密的。

11 requests对象

r.url

r.text

r.headers

12 response对象

response.request 对应的请求对象

response.raw socket上直接获得的数据

response.text 根据响应头进行解码的文本数据

response.content 不解码,返回二进制数据

response.json() 对返回数据进行json解码

response.headers 词典形式存储返回的headers

response.cookies 词典形式存储返回的cookies

希望本文所述对大家python程序设计有所帮助。

希望与广大网友互动??

点此进行留言吧!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值