python网络请求的库_【Python 模块】 requests 基本使用

安装 & 加载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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值