python - requests 库的学习

文章目录

      • 使用 Requests 发送网络请求
        • 一、安装:
        • 二、模拟简单的 HTTP 请求:
          • a、传递 URL 参数:
          • b、定制请求头 `headers`
        • 三、响应内容:
          • a、二进制响应内容:
          • b、Json响应内容:
        • 三、cookie 持久化:

使用 Requests 发送网络请求

一、安装:

pip install requests

# pipenv 安装
pipenv install request

导入 Request模块 :

import requests

二、模拟简单的 HTTP 请求:

注意 :post, put 请求如果传入的是json格式的数据,必须得用 json 参数,不然会返回请求参数不正确

示例 :

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

# post 请求,data 代表传入参数
r = requests.post('http://httpbin.org/post', data = {'key':'value'})
# or
r = requests.post('http://httpbin.org/post', json = {'key':'value'})

# put 请求
r = requests.put('http://httpbin.org/put', data = {'key':'value'})

# delete 请求
r = requests.delete('http://httpbin.org/delete')

# head 请求
r = requests.head('http://httpbin.org/get')

# options 请求
r = requests.options('http://httpbin.org/get')

a、传递 URL 参数:

例如, httpbin.org/get?key=val

Requests 允许你使用 params 关键字参数,以一个字符串字典来提供这些参数。举例来说,如果你想传递 key1=value1key2=value2httpbin.org/get ,那么你可以使用如下代码:

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)

# 打印输出结果 : http://httpbin.org/get?key2=value2&key1=value1

注意:字典中的值为 None ,不会被添加到 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
b、定制请求头 headers

如果你想为请求添加 HTTP头部, 只要简单的传递一个 distheaders 参数就可以了

例如,在前一个示例中我们没有指定 content-type:

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

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

注意: 定制 header 的优先级低于某些特定的信息源,例如:

  • 如果在 .netrc 中设置了用户认证信息,使用 headers= 设置的授权就不会生效。而如果设置了 auth= 参数,.netrc 的设置就无效了。
  • 如果被重定向到别的主机,授权 header 就会被删除。
  • 代理授权 header 会被 URL 中提供的代理身份覆盖掉。
  • 在我们能判断内容长度的情况下,header 的 Content-Length 会被改写。

更进一步讲,Requests 不会基于定制 header 的具体情况改变自己的行为。只不过在最后的请求中,所有的 header 信息都会被传递进去。

注意: 所有的 header 值必须是 string、bytestring 或者 unicode。尽管传递 unicode header 也是允许的,但不建议这样做。

三、响应内容:

先通过请求一个url地址,获取服务器响应信息:

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

>>> r.text   
u'[{"repository":{"open_issues":0,"url":"https://github.com/...
字段 描述
r.text 获取响应文本
r.json() 获取响应文本,json 格式的内容
r.content 获取响应文本,二进制响应内容
r.encoding 获取字符编码格式
r.status_code 响应状态码
r.url 获取请求的 url
r.headers 获取响应的信息头
r.cookies 获取响应的 Cookies 消息
r.is_redirect 校验 url 是否有重定向
a、二进制响应内容:

也能以字节的方式访问请求响应体,对于非文本请求

>>> r.content
b'[{"repository":{"open_issues":0,"url":"https://github.com/...

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

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

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

>>> i = Image.open(BytesIO(r.content))
b、Json响应内容:
>>> import requests

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

如果 JSON 解码失败, r.json() 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问 r.json() 将会抛出 ValueError: No JSON object could be decoded 异常。

三、cookie 持久化:

要在会话中保留状态,可以使用request.Session()。

Session可以使用get,post等方法,Session对象在请求时允许你保留一定的参数和自动设置cookie

# 导入模块
from requests.sessions import Session

# 创建实例
s = Session()
data = {'username':'mouse','password':'123456}
headers = {'Content-Type':'application/json'}
r = s.post(url='https://www.imooc.com', json=data, headers=headers)

你可能感兴趣的:(Python)