Python requests库

一、requests基础环境导入

import requests
import json
# 异常捕获专用导入
from requests.exceptions import HTTPError, ConnectionError, Timeout

二、五大常用请求方法:GET/POST/PUT/DELETE/HEAD

测试地址:https://www.baidu.com/

1. GET请求(查询数据,默认自动重定向)

  1. params:url拼接参数,自动拼接?key=val&key2=val2
url = "https://www.baidu.com"
param = {"wd": "python"}
res = requests.get(url, params=param)
# 实际访问地址:https://www.baidu.com?wd=python
  1. 重定向规则
  • GET/HEAD:allow_redirects=True默认开启自动跳转,302跟随跳转最终返回200
  • POST/PUT/DELETE:allow_redirects=False默认关闭跳转,遇到302直接返回302状态码
  • 开启POST自动重定向写法:res = requests.post(url, allow_redirects=True)

2. POST请求(提交数据,三种传参方式)

参数 数据格式 使用场景
data form表单x-www-form-urlencoded 普通表单提交
json application/json json格式接口提交
files 二进制文件对象 文件上传

3. PUT/DELETE

  • PUT:全量修改资源;DELETE:删除资源
  • 访问百度首页均返回302,原因:静态网页仅支持GET,不接收修改/删除请求

三、Response响应对象五大常用属性

res = requests.get("https://www.baidu.com")
res.status_code      # 状态码200/302/404/500
res.text             # 字符串源码(容易乱码)
res.content          # 二进制字节,图片/文件下载专用,乱码用res.content.decode("utf-8")
res.cookies          # RequestsCookieJar对象,可遍历、可字典取值
res.headers          # 响应头字典
res.history          # 重定向跳转记录列表

补充:Cookie遍历

res.cookies不是列表/字典,是RequestsCookieJar

# 1.循环遍历逐个取出cookie
for ck in res.cookies:
    print(ck.name, ck.value)
# 2.字典方式取值
print(res.cookies.get("BAIDUID"))

补充:raise_for_status()异常校验

try:
    res = requests.get(url, timeout=3)
    res.raise_for_status() # 4xx/5xx主动抛出HTTPError;3xx不报错
except HTTPError:
    print("接口状态异常")
except ConnectionError:
    print("网络连接失败")
except Timeout:
    print("请求超时")

四、文件上传(单文件+循环多文件)

requests.post依靠files={字段名:打开的文件对象}实现上传,字典key=后端接收字段名,value=rb打开的文件

1. 单个文件上传

url = "http://xxx.com"
file_path = "./test.txt"
with open(file_path, "rb") as f: # rb二进制只读,上传固定格式
    files = {"file": f} # key:后端字段名,value:本地打开文件
    res = requests.post(url, files=files)
print(res.text)

2. 循环批量上传多文件(拆解循环逻辑)

# 字典:key=后端字段名,value=本地文件路径
file_map = {
    "file1": "./file1.txt",
    "file2": "./file2.txt"
}
result = {} # 存储每个文件上传后的返回结果

# 循环等价拆分:先file1上传,再file2上传,字段名自动变化
for field_name, path in file_map.items():
    with open(path, "rb") as file_obj:
        single_file = {field_name: file_obj}
        resp = requests.post(url, files=single_file)
        result[field_name] = resp.text
print(result)

笔记备注:循环每次field_name自动变更,因此两次上传字段分别是file1、file2,不会重名。

五、代理配置(Proxy中间人转发,4种配置方式)

代理原理:充当客户端与目标服务器中间人,转发请求/响应;作用:隐藏本机IP、突破访问限制
生效优先级:单次proxies参数 > Session代理 > 系统环境变量

1. 单次请求配置代理(仅当前请求生效)

import requests
proxies = {
    'http': 'http://xxx.com:8080',
    'https': 'https://xxx.com:8080'
}
response = requests.get(url, proxies=proxies)

2. 带账号密码的代理(付费代理)

格式:协议://用户名:密码@代理IP:端口

import requests
proxies = {
    'http': 'http://username:password@xxx.com:8080',
    'https': 'https://username:password@xxx.com:8080'
}
response = requests.get(url, proxies=proxies)

3. Session全局代理(同会话全部请求自动走代理)

import requests
proxy = 'http://xxx.com:8080'
session = requests.Session()
session.proxies = {'http': proxy, 'https': proxy}
# 无需传proxies参数
response = session.get(url)

4. OS环境变量全局代理(整个程序所有请求自动读取)

import requests
import os
# 设置系统环境变量
os.environ['HTTP_PROXY'] = 'http://xxx.com:8080'
os.environ['HTTPS_PROXY'] = 'https://xxx.com:8080'
# 不用配置proxies
response = requests.get(url)

六、Session会话对象

自动保存cookie,跨请求保留登录状态,爬虫登录必备

session = requests.Session()
session.post("登录接口", data={"user":"xxx","pwd":"xxx"})
session.get("个人中心地址") # 自动携带登录cookie
Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐