栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python HTTP library~Requests

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python HTTP library~Requests

官网:Requests
接口:Main Interface

Requests 是一个第三方的http包。请求参数不需要手动拼接。

安装依赖
pip install requests
发送请求

Requests 支持的请求方式POST、GET、OPTIONS、DELETE、PUT、HEAD、PATCH
示例

import requests

	r = requests.get('https://api.github.com/events',params={'key1': 'value1', 'key2': 'value2'})
	r = requests.post('https://httpbin.org/post', data={'key': 'value'})
	r = requests.put('https://httpbin.org/put', data={'key': 'value'})
	r = requests.delete('https://httpbin.org/delete')
	r = requests.head('https://httpbin.org/get')
	r = requests.options('https://httpbin.org/get')
	

当字典中某个key的值为None,则该key将不会被添加到url的querey string中

import requests

    payload = {'key1': 'value1', 'key2': ['value2','value3'],'key3': None}
    response = requests.get('https://httpbin.org/get', params=payload)
    print(response.url)

输出结果   https://httpbin.org/get?key1=value1&key2=value2&key2=value3
响应结果

Requests 会自动解码服务器返回的响应内容。响应内容的编码依赖headers中的设置。
Requests 会自动对gzip、deflate 类型的响应结果解码,而br类型解码则需要安装Brotli包(brotli 或 brotlicffi)

response.text

response.content

response.json()
json解码失败将抛出异常

response.raw
使用此方式需要在初始化reqeust时将stream置为`True`
with open(filename, 'wb') as fd:
    for chunk in r.iter_content(chunk_size=128):
        fd.write(chunk)
自定义header
headers = {'user-agent': 'my-app/0.0.1'}
reqeust.get('https://api.github.com/events',params={'key1': 'value1', 'key2': 'value2'},headers=headers)

发送json 数据
requests.post('https://api.github.com/some/endpoint',json={'some': 'data'}
上传文件
url = 'https://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}

r = requests.post(url, files=files)
r.text
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/829334.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号