智用指南
第二套高阶模板 · 更大气的阅读体验

用Python脚本轻松发送requests请求

发布时间:2025-12-09 15:15:24 阅读:332 次

写爬虫、调接口、自动化测试,很多时候都绕不开发HTTP请求。在ref="/tag/136/" style="color:#8B0506;font-weight:bold;">Python里,requests库就像一把万能钥匙,简单几行代码就能搞定网页抓取或API交互。

安装requests库

大多数情况下,直接用pip安装即可:

pip install requests

装好之后,导入就能用,不需要额外配置。

最基础的GET请求

比如你想获取某个网页的内容,像查天气、拿新闻标题,用get()方法就行:

import requests

response = requests.get("https://httpbin.org/get")
print(response.status_code)  # 看状态码是不是200
print(response.text)       # 打印返回内容

带参数的请求

有些接口需要传参,比如搜索关键词。手动拼URL太麻烦,requests支持用字典传参:

params = {"q": "python教程", "page": 1}
response = requests.get("https://example.com/search", params=params)
# 实际请求的是 https://example.com/search?q=python教程&page=1

模拟登录常用的POST请求

提交表单、登录账号通常用POST。把用户名密码放进data字典,发出去就行:

data = {"username": "test", "password": "123456"}
response = requests.post("https://example.com/login", data=data)

if "登录成功" in response.text:
    print("登录OK")

加请求头避免被拦截

有些网站会屏蔽没有User-Agent的请求。这时候得伪装成浏览器:

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"
}
response = requests.get("https://example.com", headers=headers)

加上这个头,很多反爬机制就绕过去了。

处理JSON响应更方便

现在很多接口返回的是JSON数据。requests自带解析功能,不用自己用json.loads()

response = requests.get("https://api.github.com/users/octocat")
data = response.json()  # 直接转成Python字典
print(data["name"])

超时和异常别忽略

网络不稳定,不设超时可能卡住整个脚本。建议每次请求都加上timeout

try:
    response = requests.get("https://slow-site.com", timeout=5)
except requests.exceptions.Timeout:
    print("请求超时了")

这样程序不会一直卡着,用户体验也好一些。

小技巧:保持会话状态

如果要连续操作多个页面,比如先登录再访问个人中心,用Session对象更省事:

with requests.Session() as session:
    session.post("https://example.com/login", data={"user": "xxx"})
    resp = session.get("https://example.com/dashboard")
    print(resp.text)

Cookie自动管理,不用手动提取传递。

日常写个小工具查信息、批量拉数据,requests完全够用。语法清晰,出错容易调试,是写Python脚本离不开的帮手。