安装 & 加载pip3 install requests -i https://mirrors.aliyun.com/pypi/simple/
import requests
GET 请求# 普通请求
r = requests.get('https://bigdataboy.cn/')
# 带 Query 参数,等价于 https://bigdataboy.cn/?key1=value1&key2=value2
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://bigdataboy.cn/', params=params)
# 带 Headers
headers = {'user-agent': 'anoyi-app/0.0.1'}
r = requests.get('https://bigdataboy.cn/', headers=headers)
# 带 Basic Authentication
r = requests.get('https://bigdataboy.cn/', auth=('user', 'pass'))
POST 请求POST 请求 - 表单提交
r = requests.post('https://bigdataboy.cn/', data={'key':'value'})
POST 请求 - x-www-form-urlencoded
headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}
r = requests.post('https://bigdataboy.cn/', headers=headers, data='key=value')
POST 请求 - application/json
payload = {'some': 'data'}
r = requests.post('https://bigdataboy.cn/', json=payload)
其他请求# PUT
r = requests.put('https://bigdataboy.cn/', data={'key':'value'})
# DELETE
r = requests.delete('https://bigdataboy.cn/')
# HEAD
r = requests.head('https://bigdataboy.cn/')
# OPTIONS
r = requests.options('https://bigdataboy.cn/')
网络响应 - Reponse基本信息
# 状态码
r.status_code
# 响应头
r.headers
# 响应 Cookie
r.cookies
返回结果
# 文本内容
r.text
# 二进制
r.content
# JSON
r.json()
# 流
r = requests.get('https://bigdataboy.cn/', stream=True)
r.raw.read(10)
常用方法URL编码
from requests.utils import quote
quote('a b') -> 'a%20b'
URL解码
from requests.utils import unquote
unquote('a%20b') -> 'a b'
自动推断响应编码
r.encoding = r.apparent_encoding
下载文件
r = requests.get('https://bigdataboy.cn/')
open('bigdataboy.html', 'wb').write(r.content)
上传文件
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
超时设置
# 单位:秒
requests.get('https://bigdataboy.cn/', timeout=0.001)