该文章基于官方文档进行整理,数据接口均为官方文档中提供
按照官方的文档是说法,requests是一个非转基因的Python HTTP 库。功能强大,语法简洁。可以说,使用Python写Web程序,requests是不可避免的。
虽然说requests是使用简单,但是其大部分功能并非需要常常用到。但是在需要用到时又要去查文档就比较繁琐。所以也是想说做一个整理和总结。方便自己也方便他人。
# 安装。注意,千万别安装成request,别少了末尾的s
pip install resquests
基础请求
首先导入Requests模块
import requests
各类请求方式
r = requests.get('http://httpbin.org/get')
# post带参
r = requests.post('http://httpbin.org/post', data={'key': 'value'})
r = requests.put('http://httpbin.org/put', data={'key': 'value'})
r = requests.delete('http://httpbin.org/delete')
r = requests.head('http://httpbin.org/get')
r = requests.options('http://httpbin.org/get')
requests允许传递URL参数,通过传递参数键值对给params
变量,requests会自动构建好对应的URL。
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
# 注意,字典里值为的None的键并不会被拼接到URL中
# 同时,你还可以将列表作为值进行传入
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)
>>> http://httpbin.org/get?key1=value1&key2=value2&key2=value3
响应内容
通过text
返回响应内容的Unicode型数据。requests会自动解码来自服务器的内容。
# 在需要读取文本信息时,可使用text进行获取
r = requests.get('http://httpbin.org/get')
r.text
通过content
返回响应内容的bytes型(二进制)数据。
# 在需要获取文件时,可通过content获取
# 例如获取一张图片并保存
r = requests.get('http://httpbin.org/get/xxx.jpg')
with open('example.jpg', 'wb') as img:
img.write(r)
通过json()
处理响应的json数据。
import requests
r = requests.get('http://httpbin.org/get')
r.json()
定制请求头
为请求添加头部,只需要传递dict
给headers
参数即可
# HTTP头部大小写是不敏感的
headers = {
'token': token,
'content-type': 'application/json'
}
url = 'http://httpbin.org/get'
r = requests.get(url, headers=headers)
POST发送非表单形式数据
在post请求带有请求体时,可以使用json
模块对数据进行编码
url = 'http://httpbin.org/get'
body = {'data': data}
r = requests.post(url, data=json.dumps(body))
除了使用json
进行编码外,还可以直接对json
参数进行传值
url = 'http://httpbin.org/get'
body = {'data': data}
r = requests.post(url, json=body)
通过POST上传文件
使用open
方法以二进制形式读取文件后,即可方便地进行文件上传
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
# 同时,可以显式地设置文件名、文件类型和请求头
url = 'http://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
发送cookie
可通过给参数cookies
传参进行cookie的传递
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
# 在跨域使用时,可以通过RequestsCookieJar进行域名和路径的定义
jar = requests.cookies.RequestsCookieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=jar)
获取响应信息
通过status_code
获取响应状态码
r = requests.get('http://httpbin.org/get')
r.status_code
>>> 200
# requests内置一个状态码查询对象
print(r.status_code == requests.codes.ok)
>>> True
# 如果发生了4xx或者5xx的错误响应,可以使用raise_for_status()函数来抛出异常
bad_r = requests.get('http://httpbin.org/status/404')
bad_r.status_code
>>> 404
bad_r.raise_for_status()
# 如果请求没有发生错误,则raise_for_status()返回None
通过headers
获取响应头
r = requests.get('http://httpbin.org/get')
r.headers
>>> {
'content-encoding': 'gzip',
'transfer-encoding': 'chunked',
'connection': 'close',
'server': 'nginx/1.0.4',
'x-runtime': '148ms',
'etag': '"e1ca502697e5c9317743dc078f67693f"',
'content-type': 'application/json'
}
# 同时,我们可以通过任意大小写形式来访问这些响应头字段
r.headers['Content-Type']
>>> 'application/json'
r.headers.get('content-type')
>>> 'application/json'
通过cookies
获取cookie数据
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
r.cookies['example_cookie_name']
>>> 'example_cookie_value'
重定向与请求历史
默认情况下,除了HEAD请求,requests会自动处理所有重定向
可以通过history
方法进行重定向的追踪
# 例如Github 将所有的HTTP请求重定向到HTTPS
r = requests.get('http://github.com')
r.url
>>> 'https://github.com/'
r.status_code
>>> 200
# 如果使用的时GET、OPTIONS、POST、PUT、PATCH、DELETE请求时,可以通过设置allow_redirects=False来禁用重定向
r = requests.get('http://github.com', allow_redirects=False)
r.status_code
>>> 301
# 也可以通过设置allow_redirects=True来启用HEAD请求的重定向
r = requests.head('http://github.com', allow_redirects=True)
最后
这篇文章算是关于requests基础使用的总结。后续会参照官方文档,进行一些高级用法的总结。梳理一下requests的高级用法,熟练使用requests在进行Web开发时会有事半功倍的效果。