python第三方库requets使用说明

一、安装requests

由于本机安装了python3和python2,故安装requests有点区别,如下:
对于python2,则在cmd中输入py -2 -m pip install requests
如果要在python3中安装,则在cmd中输入py -3 -m pip install requests即可;

二、使用requests

1、导入requests

import requests;

2、使用requests发送请求

1)、请求发送方法:

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

前四种是比较常见的部分,后两种不常见,其中r是请求的response;

2)、

3、返回的rensponse方法解析

此处requests基本覆盖了所有的http方法,即增删改查,如下所示:

1)、获取响应内容:

此部分是在chrome控制台中的response中内容是一致的,有可能是html页面内容也有可能是一个json字符串,如下为字符串响应体;

>>> import requests
>>> r = requests.get('https://api.github.com/events')
>>> r.text
u'[{"repository":{"open_issues":0,"url":"https://github.com/...

如果确认为json字符串,则可以用方法r.json()来获取结果;
如果 JSON 解码失败, r.json() 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问 r.json() 将会抛出 ValueError: No JSON object could be decoded 异常。

字节方式响应体:

>>> r.content

Requests 会自动为你解码 gzip 和 deflate 传输编码的响应数据。

例如,以请求返回的二进制数据创建一张图片,你可以使用如下代码:

>>> from PIL import Image
>>> from io import BytesIO

>>> i = Image.open(BytesIO(r.content))

原始响应体:
在罕见的情况下,你可能想获取来自服务器的原始套接字响应,那么你可以访问 r.raw。 如果你确实想这么干,那请你确保在初始请求中设置了 stream=True。具体你可以这么做:

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

但一般情况下,你应该以下面的模式将文本流保存到文件:

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

使用 Response.iter_content 将会处理大量你直接使用 Response.raw 不得不处理的。 当流下载时,上面是优先推荐的获取内容方式。 Note that chunk_size can be freely adjusted to a number that may better fit your use cases.

2)、获取url全路径:

>>> payload = {'key1': 'value1', 'key2': ['value2', 'value3']}

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

3)、获取和修改response的编码:

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

4)、获取状态码

r.status_code
为方便引用,Requests还附带了一个内置的状态码查询对象:

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

如果发送了一个错误请求(一个 4XX 客户端错误,或者 5XX 服务器错误响应),我们可以通过 Response.raise_for_status() 来抛出异常:

>>> bad_r = requests.get('http://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

但是,由于我们的例子中 r 的 status_code 是 200 ,当我们调用 raise_for_status() 时,得到的是:

>>> r.raise_for_status()
None

5)、响应头

>>> r.headers
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

如上所示,使用此方法可以获取返回的response中的header信息。为一个字典,由于HTTP协议的原因其中的键不分大小写,故使用如下这种都可以获取到值:

>>> r.headers['Content-Type']
'application/json'

>>> r.headers.get('content-type')
'application/json'

6)、cookies

如下方法即为获取cookies的方法;

cks = re.cookies
for ck in cks.items():
      print ck

7)、重定向

使用如下方法可以获取到重定向信息

>>> r.history

如果有重定向信息,则此方法返回结果为[<Response [301]>]
关闭重定向添加参数allow_redirects:

>>> r = requests.get('http://github.com', allow_redirects=False)

8)、超时与异常

timeout 仅对连接过程有效,与响应体的下载无关。

>>> requests.get('http://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)

所有Requests显式抛出的异常都继承自 requests.exceptions.RequestException:ConnectionError、HTTPError、Timeout、TooManyRedirects。

以上内容参考自:http://docs.python-requests.org/zh_CN/latest/user/quickstart.html#id7

猜你喜欢

转载自blog.csdn.net/df0128/article/details/82765663
今日推荐