python三方库之requests的快速上手


Posted in Python onMarch 04, 2019

本文基于2.21.0

发送请求

发送GET请求:

r = requests.get('https://api.github.com/events')

发送POST请求:

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

其他请求接口与HTTP请求类型一致,如PUT, DELETE, HEAD, OPTIONS等。

在URL查询字符串中使用参数

给params参数传递一个字典对象:

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.get('https://httpbin.org/get', params=payload)
>>> print(r.url)
https://httpbin.org/get?key2=value2&key1=value1

字典的值也可以是一个列表:

>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
>>> r = requests.get('https://httpbin.org/get', params=payload)
>>> print(r.url)
https://httpbin.org/get?key1=value1&key2=value2&key2=value3

参数中值为None的键值对不会加到查询字符串

文本响应内容

Response对象的text属性可以获取服务器响应内容的文本形式,Requests会自动解码:

>>> r = requests.get('https://api.github.com/events')
>>> r.text
'[{"id":"9167113775","type":"PushEvent","actor"...

访问Response.text时,Requests将基于HTTP头猜测响应内容编码。使用Response.encoding属性可以查看或改变Requests使用的编码:

>>> r.encoding
'utf-8'
>>> r.encoding = 'ISO-8859-1'

二进制响应内容

Response对象的content属性可以获取服务器响应内容的二进制形式:

>>> r.content
b'[{"id":"9167113775","type":"PushEvent","actor"...

JSON响应内容

Response对象的json()方法可以获取服务器响应内容的JSON形式:

>>> r = requests.get('https://api.github.com/events')
>>> r.json()
[{'repo': {'url': 'https://api.github.com/...

如果JSON解码失败,将抛出异常。

原始响应内容

在极少情况下,可能需要访问服务器原始套接字响应。通过在请求中设置stream=True参数,并访问Response对象的raw属性实现:

>>> r = requests.get('https://api.github.com/events', stream=True)
>>> r.raw
<urllib3.response.HTTPResponse object at 0x101194810>
>>> r.raw.read(10)
'\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03'

通常的用法是用下面这种方式将原始响应内容保存到文件,Response.iter_content方法将自动解码gzip和deflate传输编码:

with open(filename, 'wb') as fd:
  for chunk in r.iter_content(chunk_size=128):
    fd.write(chunk)

定制请求头

传递一个dict对象到headers参数,可以添加HTTP请求头:

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}

>>> r = requests.get(url, headers=headers)

定制的header的优先级较低,在某些场景或条件下可能被覆盖。

所有header的值必须是string, bytestring或unicode类型。但建议尽量避免传递unicode类型的值

更复杂的POST请求

发送form-encoded数据

给data参数传递一个字典对象:

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("https://httpbin.org/post", data=payload)

如果有多个值对应一个键,可以使用由元组组成的列表或者值是列表的字典:

>>> payload_tuples = [('key1', 'value1'), ('key1', 'value2')]
>>> r1 = requests.post('https://httpbin.org/post', data=payload_tuples)
>>> payload_dict = {'key1': ['value1', 'value2']}
>>> r2 = requests.post('https://httpbin.org/post', data=payload_dict)

发送非form-encoded数据

如果传递的是字符串而非字典,将直接发送该数据:

>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))

或者可以使用json参数自动对字典对象编码:

>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)

a) 如果在请求中使用了data或files参数,json参数会被忽略。b) 在请求中使用json参数会改变Content-Type的值为application/json

POST一个多部分编码(Multipart-Encoded)的文件

上传文件:

>>> url = 'https://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)

显式地设置文件名,内容类型(Content-Type)以及请求头:

>>> 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)

甚至可以发送作为文件接收的字符串:

>>> url = 'http://httpbin.org/post'
>>> files = {'file': ('report.csv', 'some,data,to,send\nanother,row,to,send\n')}
>>> r = requests.post(url, files=files)

如果发送的文件过大,建议使用第三方包requests-toolbelt做成数据流。

强烈建议以二进制模式打开文件,因为Requests可能以文件中的字节长度来设置Content-Length

响应状态码

Response对象的status_code属性可以获取响应状态:

>>> r = requests.get('https://httpbin.org/get')
>>> r.status_code
200

requests库还内置了状态码以供参考:

>>> r.status_code == requests.codes.ok
True

如果请求异常(状态码为4XX的客户端错误或5XX的服务端错误),可以调用raise_for_status()方法抛出异常:

>>> bad_r = requests.get('https://httpbin.org/status/404')
>>> bad_r.status_code
404
>>> bad_r.raise_for_status()
Traceback (most recent call last):
 File "requests/models.py", line 832, in raise_for_status
  raise http_error
requests.exceptions.HTTPError: 404 Client Error

响应头

Response对象的headers属性可以获取响应头,它是一个字典对象,键不区分大小写:

>>> 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

Response对象的cookies属性可以获取响应中的cookie信息:

>>> url = 'http://example.com/some/cookie/setting/url'
>>> r = requests.get(url)
>>> r.cookies['example_cookie_name']
'example_cookie_value'

使用cookies参数可以发送cookie信息:

>>> url = 'https://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)

Response.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 = 'https://httpbin.org/cookies'
>>> r = requests.get(url, cookies=jar)
>>> r.text
'{"cookies": {"tasty_cookie": "yum"}}'

重定向及请求历史

requests默认对除HEAD外的所有请求执行地址重定向。Response.history属性可以追踪重定向历史,它返回一个list,包含为了完成请求创建的所有Response对象并由老到新排序。

下面是一个HTTP重定向HTTPS的用例:

>>> r = requests.get('http://github.com/')
>>> r.url
'https://github.com/'
>>> r.status_code
200
>>> r.history
[<Response [301]>]

使用allow_redirects参数可以禁用重定向:

>>> r = requests.get('http://github.com/', allow_redirects=False)
>>> r.status_code
301
>>> r.history
[]

如果使用的是HEAD请求,也可以使用allow_redirects参数允许重定向:

>>> r = requests.head('http://github.com/', allow_redirects=True)
>>> r.url
'https://github.com/'
>>> r.history
[<Response [301]>]

请求超时

使用timeout参数设置服务器返回响应的最大等待时间:

>>> requests.get('https://github.com/', timeout=0.001)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
requests.exceptions.Timeout: HTTPConnectionPool(host='github.com', port=80): Request timed out. (timeout=0.001)

错误及异常

  • ConnectionError:网络异常,比如DNS错误,连接拒绝等。
  • HTTPError:如果请求返回4XX或5XX状态码,调用Response.raise_for_status()会抛出此异常。
  • Timeout:连接超时。
  • TooManyRedirects:请求超过配置的最大重定向数。
  • RequestException:异常基类。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python抓取网页图片并放到指定文件夹
Apr 24 Python
python的re模块应用实例
Sep 26 Python
python 获取网页编码方式实现代码
Mar 11 Python
python中闭包Closure函数作为返回值的方法示例
Dec 17 Python
python使用正则表达式来获取文件名的前缀方法
Oct 21 Python
pytorch使用Variable实现线性回归
May 21 Python
Python实现计算对象的内存大小示例
Jul 10 Python
用python中的matplotlib绘制方程图像代码
Nov 21 Python
Python如何使用input函数获取输入
Aug 06 Python
Python 打印自己设计的字体的实例讲解
Jan 04 Python
python 爬取吉首大学网站成绩单
Jun 02 Python
python ConfigParser库的使用及遇到的坑
Feb 12 Python
django的ORM模型的实现原理
Mar 04 #Python
Python中按值来获取指定的键
Mar 04 #Python
python实现合并两个排序的链表
Mar 03 #Python
Python给图像添加噪声具体操作
Mar 03 #Python
django配置连接数据库及原生sql语句的使用方法
Mar 03 #Python
更新修改后的Python模块方法
Mar 03 #Python
详解js文件通过python访问数据库方法
Mar 03 #Python
You might like
全国FM电台频率大全 - 31 新疆维吾尔族自治区
2020/03/11 无线电
PHP获取文件相对路径的方法
2015/02/26 PHP
PHP读取CSV大文件导入数据库的实例
2017/07/24 PHP
php检查函数必传参数是否存在的实例详解
2017/08/28 PHP
PHP的图像处理实例小结【文字水印、图片水印、压缩图像等】
2019/12/20 PHP
风吟的小型JavaScirpt库 (FY.JS).
2010/03/09 Javascript
运算符&amp;&amp;的三个不同层次
2013/04/07 Javascript
js创建数组的简单方法
2016/07/27 Javascript
谈谈第三方App接入微信登录 解读
2016/12/27 Javascript
原生js实现鼠标跟随效果
2017/02/28 Javascript
webpack独立打包和缓存处理详解
2017/04/03 Javascript
详解Vue使用命令行搭建单页面应用
2017/05/24 Javascript
解决Vue+Element ui开发中碰到的IE问题
2018/09/03 Javascript
node链接mongodb数据库的方法详解【阿里云服务器环境ubuntu】
2019/03/07 Javascript
微信小程序swiper禁止用户手动滑动代码实例
2019/08/23 Javascript
Vuex中实现数据状态查询与更改
2019/11/08 Javascript
[44:26]DOTA2上海特级锦标赛主赛事日 - 2 胜者组第一轮#4EG VS Fnatic第二局
2016/03/03 DOTA
详解Python的迭代器、生成器以及相关的itertools包
2015/04/02 Python
python对json的相关操作实例详解
2017/01/04 Python
pandas DataFrame 警告(SettingWithCopyWarning)的解决
2019/07/23 Python
Python实现随机取一个矩阵数组的某几行
2019/11/26 Python
Python单例模式的四种创建方式实例解析
2020/03/04 Python
html5视频媒体标签video的使用方法及完整参数说明详解
2019/09/27 HTML / CSS
德国圣伯纳德草药屋:Kräuterhaus Sanct Bernhard(有中文站)
2018/08/05 全球购物
某科技软件测试面试题
2013/05/19 面试题
体育教育专业毕业生自荐信
2013/11/15 职场文书
卫校中专生的自我评价
2014/01/15 职场文书
初三化学教学反思
2014/01/23 职场文书
总裁助理岗位职责
2014/02/17 职场文书
对教师的评语
2014/04/28 职场文书
学校标语大全
2014/06/19 职场文书
大学生活动总结模板
2014/07/02 职场文书
单身证明格式样本
2015/06/15 职场文书
2016年最美孝心少年事迹材料
2016/02/26 职场文书
学校趣味运动会开幕词
2016/03/04 职场文书
mybatis中sql语句CDATA标签的用法说明
2021/06/30 Java/Android