Requests快速上手(来自官方文档)

版权声明:原创文章,未经允许不得转载。www.data-insights.cn. https://blog.csdn.net/qixizhuang/article/details/81536011

###############################################################################
#_____________________________________________________________________________#
#|      ______      ___    __________   ___      __                          |#
#|     /  __  \    /   |  /___   ___/  /   |    / /                          |#
#|    /  /  \  |  / /| |      /*      / /| |   / /      DataInsights         |#
#|   /  /   /  / / /_| |      `/     / / | |  / /                            |#
#|  /  /   /  / / ___  |     / `    / /  | | / /      [email protected]       |#
#| /  /___/  / / /   | | ___ `/__  / /   | |/ /                              |#
#|/_________/ /_/    |_|/________//_/    |___/    https://data-insights.cn/  |#
#|___________________________________________________________________________|#
###############################################################################

一、发送请求

使用Requests发送网络请求非常简单:

# 导入requests模块,若未安装需要先安装(如: pip install requests)
import requests

# GET请求
r = requests.get('https://api.github.com/events')
# POST请求
r = requests.post('http://httpbin.org/post', data={'key': 'value'})
# DELETE请求
r = requests.delete('http://httpbin.org/delete')
# HEAD请求
r = requests.head('http://httpbin.org/get')
# OPTION请求
r = requests.options('http://httpbin.org/get')

二、传递URL参数

Requests允许使用params关键字参数,以一个字符串字典来为URL提供参数:

# 将参数以字典形式传递给params
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)

# 还可以将一个列表作为值传入
payload = {'key1': 'value1', 'key2': ['value2', 'value3']}
r = requests.get('http://httpbin.org/get', params=payload)
print(r.url)

三、响应内容

我们能读取服务器响应的内容:

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

# 使用r.text时,requests会自动检测文本编码并将内容打印出来
print(r.text)

# 我们可以通过修改r.encoding来修改编码方式
print(r.encoding)   # 'utf-8'非常常见
r.encoding = 'ISO-8859-1'

# 有些HTML、XML页面指定了不同的编码,我们可以通过r.content来找到编码,然后设置r.encoding为响应的编码,这样既可正确解析r.text。

四、二进制响应内容

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

print(r.content)

# Requests会自动解码gzip、deflate传输编码的响应数据
# 例如,以请求返回的二进制数据创建一张图片:
from PIL import Image
from io import BytesIO
i = Image.open(BytesIO(r.content))

五、JSON响应内容

Requests中有一个内置的JSON解码器,可以帮助我们处理JSON数据

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

# 使用r.json()来解析json格式的数据,若解析失败,会抛出一个异常。
print(r.json())

# r.json()调用成功并不意味着响应成功,检查请求是否成功可以使用如下两个方式:
print(r.raise_for_status())
print(r.status_code)

六、原始响应内容

在罕见的情况下,我们可能想获取来自服务器的原始套接字响应:

r = requests.get('https://api.github.com/events', stream=True)
print(r.raw)
print(r.raw.read(10))

# 但一般情况下,我们应该先将文本流保存到文件
with open(filename, 'wb') as writer:
    for chunk in r.iter_content(chunk_size):
        writer.write(chunk)

七、定制请求头

如果想为请求添加HTTP头部,只要简单地传递一个dict给headers参数即可:

url = 'https://api.github.com/some/endpoint'
headers = {'user-agent': 'my-app/0.0.1'}
r = requests.get(url, headers=headers)

# 定制header的优先级低于某些特定的信息源,如:
# 1. 如果在.netrc中设置了用户认证信息,使用headers=设置的授权就不会生效,而如果设置了auth=参数,.netrc的设置就无效了。
# 2. 如果被重定向到别的主机,授权header就回被删除
# 3. 代理授权header会被URL中提供的代理身份覆盖掉
# 4. 在我们能判断内容长度的情况下,header的Content-Length会被改写。

八、更复杂的POST请求

通常,你想要发送一些编码为表单形式的数据–非常像一个HTML表单,要实现这个,只需要简单传递一个字典给data参数,它会自动编码:

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)

# data参数还接受元组的形式
payload = (('key1', 'value1'), ('key2', 'value2'))
r = requests.post('http://httpbin.org/post', data=payload)
print(r.text)

# 很多时候我们想要发送的数据并非编码为表单形式的,比如我们就是要传递string而不是按照dict解析,那么数据将会被直接发布出去
import json
url = 'https://api.github.com/some/endpoint'
payload = {'some': 'data'}
r = requests.post(url, data=json.dumps(payload))
# 除了自行对dict编码,还可以使用json参数直接传递:
r = requests.post(url, json=payload)

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

# 如:上传xls文件
url = 'http://httpbin.org/post'
files = {'file': open('report.xls', 'rb')}
r = requests.post(url, files=files)
print(r.text)

# 我们可以显式地设置文件名、文件类型和请求头:
url = 'http://httpbin.org/post'
files = {'file': ('report.xls', open('report.xls', 'rb'), \
            'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)
print(r.text)

# 我们也可以发送作为文件来接收的字符串
url = 'http://httpbin.org/post'
files = {'file': ('report.csv', 'some,data,to,send\nanather,row,to,send\n')}
r = requests.post(url, files=files)
print(r.text)

十、响应状态码

r = requests.get('http://httpbin.org/get')
print(r.status_code)

# 为方便引用,Requests还附带了一个内置的状态码查询对象
print(r.status_code == requests.codes.ok)

# 如果发送了一个错误请求(比如一个4XX客户端错误,或者5XX服务器错误响应),我们可以通过Response.raise_for_status()来抛出异常:
bad_r = requests.get('http://httpbin.org/status/404')
print(bad_r.status_code)
bad_r.raise_for_status()

十一、响应头

# 我们可以查看以字典形式展示的服务器响应头
print(r.headers)
# eg.1 一个响应头
{
    'content-encoding': 'gzip',
    'transfer-encoding': 'chunked',
    'connection': 'close',
    'server': 'nginx/1.0.4',
    'x-runtime': '148ms',
    'etag': '"e1ca502697e5c9317743dc078f67693f"',
    'content-type': 'application/json'
}

# HTTP头部是大小写不敏感的,因此如下都是可以的:
print(r.headers['Content-Type'])
print(r.headers.get('content-type')

十二、Cookie

# 通过.cookies可以访问响应所包含的cookie
url = 'http://example.com/some/cookie/setting/url'
r = requests.get(url)
print(r.cookies['example_cookie_name'])

# 要发送cookies到服务器,可以使用cookies参数:
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
r = requests.get(url, cookies=cookies)
print(r.text)

# Cookie的返回对象是RequestsCookieJar,它的行为和字典类似,但接口更完整,适合跨域名和跨路径使用,我们还可以把Cookie Jar传到Requests中:
jar = requests.cookies.RequestsokieJar()
jar.set('tasty_cookie', 'yum', domain='httpbin.org', path='/cookies')
jar.set('gross_cookie', 'blech', domain='httpbin.org', path='/elsewhere')
url = 'http://httpbin.org/cookies'
r = requests.get(url, cookies=jar)
print(r.text)

十三、重定向与请求历史

默认情况下,除了HEAD,Requests会自动处理所有重定向。
可以使用响应对象的history方法来追踪重定向,Response.history是一个Response对象的列表,这个对象列表按照从最老到最近的请求进行排序。

r = requests.get('http://github.com')
print(r.url)
print(r.status_code)
print(r.history)

# 如果使用的是GET、OPTIONS、POST、PUT、PATCH或者DELETE,那么我们可以通过allow_redirects参数禁用重定向处理:
r = requests.get('http://github.com', allow_redirects=False)
print(r.status_code)
print(r.history)

# 如果使用了HEAD,我们也可以启用重定向:
r = requests.head('http://github.com', allow_redirects=True)
print(r.url)
print(r.history)

十四、超时

timeout参数用于设置等待响应的最长时间,即requests会在等待该时间之后停止等待响应。若不设置该参数,程序可能会永远失去响应:
requests.get(‘http://github.com’, timeout=0.001)

十五、错误与异常

  • 遇到网络问题时,Requests会抛出一个ConnectionError异常
  • 如果HTTP请求返回了不成功的状态码,Response.raise_for_status()会抛出一个HTTPError异常
  • 若请求超时,则抛出Timeout异常
  • 若请求超过了设定的最大重定向次数,则抛出TooManyRedirects异常
  • 所有Requests显式抛出的异常都继承自requests.exceptions.RequestException

猜你喜欢

转载自blog.csdn.net/qixizhuang/article/details/81536011
今日推荐