网络请求,这个库让HTTP变得像呼吸一样自然


在这里插入图片描述

玩转网络请求,这个库让HTTP变得像呼吸一样自然

第一部分 | 背景:当 urllib 遇上咖啡杯

在 Python 标准库里,urllib 就像一台老式咖啡机——功能齐全,但按钮太多、说明书太厚。
当你只想“来一杯拿铁”时,却要研究锅炉压力、水温曲线、研磨粗细……于是,Requests 出现了:它把 HTTP 变成了一句“服务员,一杯拿铁”。
你只需要告诉它 URL、参数、Header,它就能把剩下的研磨、萃取、拉花全部搞定。
接下来,我们将一起拆开这台“全自动咖啡机”,看看它到底藏了什么黑科技。

第二部分 | Requests 是什么?

Requests 是一个第三方 HTTP 客户端库,口号只有一个词:HTTP for Humans
它把繁琐的底层细节封装成人类友好的 API,让你用几行代码完成 GET、POST、PUT、DELETE 等所有常见操作,同时自动处理编码、Cookie、SSL、超时、Keep-Alive 等“锅炉压力”问题。

第三部分 | 一行命令,把“咖啡机”搬回家

pip install requests

如果你是 Anaconda 用户,也可以:

conda install requests

这条命令会把 Requests 及其唯一依赖 urllib3certificharset-normalizeridna 一并装好,开箱即用。

第四部分 | 5 个核心 API,5 行代码入门

1. 最简单的 GET

import requests
r = requests.get("https://httpbin.org/get")   # 发起 GET 请求
print(r.status_code)                          # 200 表示成功
print(r.text[:100])                           # 打印前 100 字符看看
行号说明
1导入库
2向目标地址发 GET,返回 Response 对象
3查看 HTTP 状态码
4查看响应体文本

2. 带查询参数的 GET

params = {"q": "python", "page": 2}
r = requests.get("https://httpbin.org/get", params=params)
print(r.url)      # 自动拼接 https://httpbin.org/get?q=python&page=2

3. 发送 JSON 的 POST

payload = {"name": "Alice", "age": 23}
r = requests.post("https://httpbin.org/post", json=payload)
print(r.json()["json"])   # 服务器原样返回的 JSON

4. 下载二进制文件

r = requests.get("https://httpbin.org/image/png")
with open("logo.png", "wb") as f:
    f.write(r.content)    # content 是 bytes 类型

5. 自定义 Header 与超时

headers = {"User-Agent": "CoffeeBot/1.0"}
r = requests.get("https://httpbin.org/headers",
                 headers=headers,
                 timeout=3)   # 3 秒无响应抛异常

第五部分 | 5 个实战场景,把 Requests 玩出花

场景 1:调用天气 API

import requests, datetime

API_KEY = "YOUR_KEY"
city = "Shanghai"
url = f"https://api.openweathermap.org/data/2.5/weather"
params = {"q": city, "appid": API_KEY, "units": "metric"}

r = requests.get(url, params=params, timeout=5)
data = r.json()
print(f"{city} 温度 {data['main']['temp']}°C, 体感 {data['main']['feels_like']}°C")

场景 2:模拟登录获取 Cookie

session = requests.Session()                       # 创建会话
login_data = {"username": "admin", "password": "123456"}
session.post("https://httpbin.org/post", data=login_data)

r = session.get("https://httpbin.org/cookies")     # 复用 Cookie
print(r.json())

场景 3:上传文件

files = {"file": ("report.csv", open("report.csv", "rb"), "text/csv")}
r = requests.post("https://httpbin.org/post", files=files)
print(r.json()["files"])

场景 4:流式下载大文件

url = "https://speed.hetzner.de/100MB.bin"
with requests.get(url, stream=True) as r:
    r.raise_for_status()
    with open("100MB.bin", "wb") as f:
        for chunk in r.iter_content(chunk_size=8192):
            if chunk:           # 过滤保活 chunk
                f.write(chunk)

场景 5:并发请求(借助线程池)

from concurrent.futures import ThreadPoolExecutor

urls = ["https://httpbin.org/delay/1"] * 10

def fetch(url):
    return requests.get(url, timeout=5).status_code

with ThreadPoolExecutor(max_workers=5) as pool:
    for status in pool.map(fetch, urls):
        print(status)

第六部分 | 3 个常见 Bug 与“急救包”

Bug 1:SSL 证书验证失败

错误信息: SSLCertVerificationError

# 错误代码
r = requests.get("https://self-signed.badssl.com")

解决: 开发环境可加 verify=False,生产环境务必替换有效证书。

r = requests.get("https://self-signed.badssl.com", verify=False)

Bug 2:超时未捕获导致程序挂起

错误信息: requests.exceptions.Timeout

# 错误代码
r = requests.get("https://httpbin.org/delay/10", timeout=2)

解决: 捕获异常并重试。

from requests.exceptions import Timeout

try:
    r = requests.get("https://httpbin.org/delay/10", timeout=2)
except Timeout:
    print("请求超时,稍后重试")

Bug 3:编码乱码

现象: 中文变成“微信”

# 错误代码
r = requests.get("https://httpbin.org/html")
print(r.text)          # 浏览器正常,终端乱码

解决: 手动指定正确编码或让库自动猜测。

r.encoding = r.apparent_encoding   # 自动猜测
print(r.text)

第七部分 | 总结:把 HTTP 变成呼吸

Requests 用一句话概括就是:把 HTTP 的复杂留给自己,把简单留给开发者
无论你是想爬取数据、调用 REST API、上传文件还是做自动化测试,只要记住:

import requests
r = requests.get("https://...")

剩下的研磨、萃取、拉花,Requests 都帮你做好了。
现在,去为你的项目“点一杯拿铁”吧!
如果你觉得文章还不错,请大家 点赞、分享、留言 下,因为这将是我持续输出更多优质文章的最强动力!

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

嘎啦AGI实验室

你的鼓励是我创作最大的动力~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值