Python 网络请求库 requests 的简单使用

Python 网络请求库 requests 的简单使用

正文

安装

pip install requests

你也可以查看 官方安装入口

使用

我们常用的就是 GET、 POST 请求方式,其他方式大同小异。使用前请先

import requests

GET 请求

  1. 简单的 GET 请求
requests.get("https://api.github.com/events")
  1. 通过 url 传递参数
params = {"key1": "value1", "key2": "value2"}
r = requests.get("https://httpbin.org/get", params=params)

# 可以通过打印 r.url 验证
print(r.url)
# https://httpbin.org/get?key1=value1&key2=value2&key2=value3
  1. HTTP BASIC AUTH(post 方式同理)
params = {"key1": "value1", "key2": "value2"}
http_basic_auth = requests.auth.HTTPBasicAuth("username", "password")
requests.get(url, params=params, auth=http_basic_auth) 
  1. 设置超时时间(post 方式同理)
# 单位: 秒
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)

POST 请求

  1. 简单的 post 请求
requests.post("https://httpbin.org/post", data = {"key":"value"})
  1. 请求体为 json 字符串
# 指定 header
header = {"Content-Type": "application/json"}
# 定义 json 对象
data_json = {"key1": "value2"}
# 转为 json 字符串(这里通过 json 库转为 json 串)
data = json.dumps(data_json)
# 发送请求
requests.post(url, data, headers=header)
  1. 传输文件
url = "https://httpbin.org/post"
files = {"file": open("report.xls", "rb")}

r = requests.post(url, files=files)
print(r.text)
## 注释
{
  ...
  "files": {
    "file": "<censored...binary...data>"
  },
  ...
}

响应结果处理

  1. 响应状态码
r = requests.get(url)
code = r.status_code
  1. 响应数据为 json (post 方式同理)
r = requests.get(url)
data = r.json()
  1. 获取响应头
r = requests.get(url)
print(r.headers)

# 注释
{
    "content-encoding": "gzip",
    "transfer-encoding": "chunked",
    "connection": "close",
    "server": "nginx/1.0.4",
    "x-runtime": "148ms",
    "etag": ""e1ca502697e5c9317743dc078f67693f"",
    "content-type": "application/json"
}

其他请求方式

requests.put("https://httpbin.org/put", data = {"key":"value"})

requests.delete("https://httpbin.org/delete")

requests.head("https://httpbin.org/get")

requests.options("https://httpbin.org/get")

总结

以上就是 requests 库的常规使用方法, 其他用法: 比如 cookie, session,exception ,请参考 官方文档