快速上手Python requests库的完整教程

Requests是一个优雅而简单的Python HTTP库,专为人类设计。它允许你轻松发送HTTP/1.1请求,无需手动添加查询字符串到URL,或者表单编码POST数据。无论是与Web API交互还是爬取网页内容,Requests都是Python开发者的首选工具。

快速上手Python requests库的完整教程

安装requests库

在开始使用requests之前,你需要先安装它。最简单的方法是通过pip安装:

pip install requests

如果你使用的是Python 3,可能需要使用pip3:

pip3 install requests

安装完成后,你可以在Python脚本中导入它:

import requests

发送第一个GET请求

GET请求是最常见的HTTP请求类型,用于从服务器获取数据。使用requests发送GET请求非常简单:

response = requests.get(‘https://api.github.com’)

这个简单的代码行会向GitHub API发送GET请求,并将响应存储在response变量中。你可以通过以下属性访问响应信息:

  • response.status_code
    HTTP状态码
  • response.text
    响应内容(文本格式)
  • response.headers
    响应头信息

处理响应内容

Requests提供了多种方式来访问服务器返回的内容。对于JSON API,你可以直接使用.json方法:

data = response.json

对于HTML内容,使用.text属性:

html_content = response.text

对于二进制内容(如图片),使用.content属性:

image_data = response.content

检查请求是否成功也很重要:

if response.status_code == 200:
print(“请求成功!”)
else:
print(f”请求失败,状态码:{response.status_code}”)

传递URL参数

在发送请求时,经常需要向URL添加查询参数。Requests让这变得非常简单,你不需要手动构建URL:

payload = {‘key1’: ‘value1’, ‘key2’: ‘value2’}
response = requests.get(‘https://httpbin.org/get’, params=payload)

这样会自动构建完整的URL:https://httpbin.org/get?key1=value1&key2=value2

发送POST请求

POST请求用于向服务器提交数据。Requests支持多种数据格式:

  • 表单数据
    使用data参数
  • JSON数据
    使用json参数
  • 文件上传
    使用files参数

发送表单数据的示例:

payload = {‘username’: ‘john’, ‘password’: ‘secret’}
response = requests.post(‘https://httpbin.org/post’, data=payload)

发送JSON数据的示例:

import json
payload = {‘name’: ‘John Doe’, ‘age’: 30}
response = requests.post(‘https://httpbin.org/post’, json=payload)

处理请求头

有时需要自定义请求头,比如设置User-Agent或添加认证信息:

headers = {
‘User-Agent’: ‘Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36’,
‘Authorization’: ‘Bearer your_token_here’
response = requests.get(‘https://api.example.com/data’, headers=headers)

错误处理与超时设置

在实际应用中,网络请求可能会失败。Requests提供了完善的错误处理机制:

try:
response = requests.get(‘https://api.example.com/data’, timeout=5)
response.raise_for_status # 如果状态码不是200,会抛出异常
except requests.exceptions.RequestException as e:
print(f”请求出错: {e}”)

设置超时可以防止程序无限期等待:

# 设置连接超时和读取超时均为5秒
response = requests.get(‘https://api.example.com/data’, timeout=(5, 5))

会话保持与Cookie管理

使用Session对象可以在多个请求之间保持某些参数,比如cookies:

with requests.Session as session:
session.headers.update({‘User-Agent’: ‘MyApp/1.0’})
# 第一个请求
response1 = session.get(‘https://httpbin.org/cookies/set/sessioncookie/123456789’)
# 第二个请求会保持相同的cookies
response2 = session.get(‘https://httpbin.org/cookies’)

完整示例

下面是一个完整的示例,演示如何使用requests库从API获取数据并处理可能的错误:

import requests
try:
# 发送GET请求
response = requests.get(
‘https://jsonplaceholder.typicode.com/posts/1’,
timeout=10
# 检查请求是否成功
response.raise_for_status
# 解析JSON响应
data = response.json
print(f”标题: {data[‘title’]}”)
print(f”内容: {data[‘body’]}”)
except requests.exceptions.Timeout:
print(“请求超时,请稍后重试”)
except requests.exceptions.HTTPError as err:
print(f”HTTP错误: {err}”)
except requests.exceptions.RequestException as err:
print(f”请求异常: {err}”)

通过本教程,你已经掌握了requests库的基本用法。这个强大而简单的库将成为你Python开发工具箱中的重要组成部分,无论是构建Web应用、与API交互还是进行数据采集,requests都能提供出色的支持。

内容均以整理官方公开资料,价格可能随活动调整,请以购买页面显示为准,如涉侵权,请联系客服处理。

本文由星速云发布。发布者:星速云。禁止采集与转载行为,违者必究。出处:https://www.67wa.com/134941.html

(0)
上一篇 2025年11月27日 上午6:26
下一篇 2025年11月27日 上午6:27
联系我们
关注微信
关注微信
分享本页
返回顶部