requests库简单的介绍

参考资料requests官方文档,崔庆才的博客

requests是基于urllib3的一个用于发起http请求的库。
这个库相较于urllib更快,更易用。

1. 发送请求

1.1 简单的尝试

访问百度,并打印返回值,及返回值的各个参数:

import requests  # 一开始要导入 Requests 模块
response = requests.get('http://www.baidu.com')  # 可以从response中获取我们想要的信息
print(response.content.decode('utf-8'))
print(type(response))
print(response.text)
print(response.cookies)

1.2 发送带参数的GET请求:

# 携带参数的get请求
import requests
data = {
    'name': 'wg',
    'age': 18
}
response = requests.get('http://httpbin.org/get', params=data)
print(response.url)  # http://httpbin.org/get?name=wg&age=18

在发送带参数的GET请求时,requests允许我们使用params关键字参数,以一个字符串字典来提供这些参数。我们打印拼接后的URL,会看到参数已经拼接成功:

print(response.url)
# http://httpbin.org/get?name=wg&age=18

1.3 发送POST请求

# 发送post请求
response = requests.post('http://httpbin.org/post')

1.4 发送更复杂的POST请求

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

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

打印结果如下:


post传递数据.png

你还可以为 data 参数传入一个元组列表。在表单中多个元素使用同一 key 的时候,这种方式尤其有效:

import requests
payload = (('key1', 'value1'), ('key1', 'value2'))
response = requests.post('http://httpbin.org/post', data=payload)
print(response.text)

打印结果如下:


多个元素使用同一个Key.png

1.5 发送别的HTTP请求

response = requests.delete('http://httpbin.org/delete')
response = requests.head('http://httpbin.org/get')
response = requests.options('http://httpbin.org/get')

2. 响应内容

Requests会自动解码来自服务器的响应。大多数 unicode 字符集都能被无缝地解码。
请求发出后,Requests 会基于 HTTP 头部对响应的编码作出有根据的推测。当你访问 response.text之时,Requests 会使用其推测的文本编码。你可以找出 Requests 使用了什么编码,并且能够使用 r.encoding 属性来改变它。

2.1 二进制响应内容

用requests获取一张图片:

import requests
response = requests.get('https://avatars3.githubusercontent.com/u/26769750?s=40&v=4')

打印content:

print(response.content)  # 打印content
打印content.png

打印content的类型:

print(type(response.content))  # 打印content的类型

把获取到的二进制数据,转换为一张图片:

import requests
response = requests.get('https://avatars3.githubusercontent.com/u/26769750?s=40&v=4')
print(response.content)
print(type(response.content))
with open('githubUserPic', 'wb') as f:
    f.write(response.content)
    f.close()

打开程序所在路径,就会看到一张叫做“githubUserPic”的图片了。

2.2 JSON响应内容

Requests 中也有一个内置的 JSON 解码器,助你处理 JSON 数据:

import requests
response = requests.get('https://api.github.com/events')
print(response.json())
如果 JSON 解码失败,response.json() 就会抛出一个异常。例如,响应内容是 401 (Unauthorized),尝试访问 response.json() 将会抛出 ValueError: No JSON object could be decoded 异常。

需要注意的是,成功调用 response.json() 并**不**意味着响应的成功。有的服务器会在失败的响应中包含一个 JSON 对象(比如 HTTP 500 的错误细节)。这种 JSON 会被解码返回。要检查请求是否成功,请使用 response.raise_for_status() 或者检查 response.status_code 是否和你的期望相同。

3. 设置请求头

直接请求http://www.zhihu.com/explore,会请求失败,并返回状态码400,表示错误请求服务器无法解析该请求
设置请求头,然后再次访问:

import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
}
response = requests.get('http://www.zhihu.com/explore', headers=headers)
print(response.text)

就可以看到正常的返回了:


设置请求头之后的返回.png

4. Cookie

如果某个响应中包含一些 cookie,你可以快速访问它们:

import requests
response = requests.get('http://www.baidu.com')
print(response.cookies)

发送cookie到服务器:

import requests
url = 'http://httpbin.org/cookies'
cookies = dict(cookies_are='working')
response = requests.get(url, cookies=cookies)
print(response.text)

打印返回值:

{
  "cookies": {
    "cookies_are": "working"
  }
}

以上内容只是简单的整理,详细的内容还请参考requests官方文档。

完。

你可能感兴趣的:(requests库简单的介绍)