Python 网络工具包 - requests

作者: Anoyi

2020-03-17 15:33

安装与加载

pip3 install requests -i https://mirrors.aliyun.com/pypi/simple/
import requests

网络请求 - Request

GET 请求

# 普通请求
r = requests.get('https://anoyi.com/')

# 带 Query 参数,等价于 https://anoyi.com/?key1=value1&key2=value2
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('https://anoyi.com/', params=payload)

# 带 Headers
headers = {'user-agent': 'anoyi-app/0.0.1'}
r = requests.get('https://anoyi.com/', headers=headers)

# 带 Basic Authentication
r = requests.get('https://anoyi.com/', auth=('user', 'pass'))

POST 请求 - form-data

r = requests.post('https://anoyi.com/', data={'key':'value'})

POST 请求 - x-www-form-urlencoded

headers = {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}
r = requests.post('https://anoyi.com/', headers=headers, data='key=value')

POST 请求 - application/json

payload = {'some': 'data'}
r = requests.post('https://anoyi.com/', json=payload)

其他请求

# PUT
r = requests.put('https://anoyi.com/', data={'key':'value'})

# DELETE
r = requests.delete('https://anoyi.com/')

# HEAD
r = requests.head('https://anoyi.com/')

# OPTIONS
r = requests.options('https://anoyi.com/')

网络响应 - Reponse

基本信息

# 状态码
r.status_code

# 响应头
r.headers

# 响应 Cookie
r.cookies

返回结果

# 文本内容
r.text

# 二进制
 r.content

# JSON
r.json()

# 流
r = requests.get('https://anoyi.com/', stream=True)
r.raw.read(10)

常用方法

1、URL 内容编码

from requests.utils import quote

quote('ab=cd&ef=gh')

2、下载文件

r = requests.get('https://anoyi.com')
open('anoyi.html', 'wb').write(r.content)

3、上传文件

files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)

4、超时设置

# 单位:秒
requests.get('https://anoyi.com', timeout=0.001)
看法

看法

昵称
邮箱