Python Requests库基本用法示例

yipeiwu_com5年前Python基础

本文实例讲述了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相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总

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

相关文章

解决pytorch报错:AssertionError: Invalid device id的问题

在服务器上训练的网络放到本地台式机进行infer,结果出现报错: AssertionError: Invalid device id 仔细检查后发现原来服务器有多个GPU,当时开启...

python3大文件解压和基本操作

先说下:所谓的大文件并不是压缩文件有多大,几十兆的文件而是解压后几百兆。其中就遇到解压不成功的情况.、读小文件时成功,大文件时失败等 def unzip_to_txt_plus(z...

浅析Python中的for 循环

Python for 和其他语言一样,也可以用来循环遍历对象,本文章向大家介绍Python for 循环的使用方法和实例,需要的朋友可与参考一下。 一个循环是一个结构,导致第一个程序要重...

Python类属性的延迟计算

所谓类属性的延迟计算就是将类的属性定义成一个property,只在访问的时候才会计算,而且一旦被访问后,结果将会被缓存起来,不用每次都计算。 优点 构造一个延迟计算属性的主要目的是为了提...

基于torch.where和布尔索引的速度比较

我就废话不多说了,直接上代码吧! import torch import time x = torch.Tensor([[1, 2, 3], [5, 5, 5], [7, 8, 9]...