目录
概述
Requests是python中一个很Pythonic的HTTP库,用于构建HTTP请求与解析响应
Requests开发哲学
- Beautiful is better than ugly.(美丽优于丑陋)
- Explicit is better than implicit.(直白优于含蓄)
- Simple is better than complex.(简单优于复杂)
- Complex is better than complicated.(复杂优于繁琐)
- Readability counts.(可读性很重要)
安装
直接安装
pip install requests
简单上手
导入模块
import requests
发送请求
#get
r = requests.get('http://httpbin.org/get')
#post
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
通过requests.get或post方法实际发出一个http请求,返回一个response对象,http://httpbin.org是一个可以测试http请求的网站
处理响应
r.text #返回响应内容主体,Requests 会自动解码来自服务器的内容
r.content #返回二进制的响应内容主体
r.json() #处理json的响应内容,返回解码后的dict
构造请求
Requests中requests.get或post这些方法实际都是通过requests.request(method, url, **kwargs)实现的,主要返回response对象,下面主要介绍这个方法的参数
method -- Request对象的请求方法.
url -- 请求的URL.
params -- (可选) 请求的URL查询字符串中要发送的字典或字节.
data -- (可选) 字典或者元组列表[(key, value)] (form-encoded), 字节, 或者文件对象包含在请求主体中发生,主要是post put使用.
json -- (可选) 包含请求主体中的json数据.
headers -- (可选) HTTP首部(请求/通用/实体首部),字典形式.
cookies -- (可选) Dict 或者 CookieJar对象包含在首部cookie字段发送.
files -- (可选) “名称”:类文件对象(或{“名称:file-tuple}”)的字典,用于分段编码上传。 file-tuple可以是2元组(“ filename”,fileobj),3元组(“ filename”,fileobj,“ content_type”)或4元组(“ filenam