玩转python: 掌握python常见库之requests(深度)

Python常用库之requests:让HTTP请求变得简单

requests是Python中最受欢迎的HTTP库之一,它让发送HTTP/1.1请求变得异常简单。相比Python内置的urllib库,requests提供了更简洁、更人性化的API,大大简化了与Web服务交互的过程。

1 requests库简介

requests库由Kenneth Reitz开发,遵循Apache 2.0开源协议。它的设计哲学是"HTTP for Humans"(为人类设计的HTTP库),确实做到了让HTTP请求变得直观易懂。

安装requests

在开始使用前,需要先安装requests库:

pip install requests

2 requests核心参数一览表

requests库的主要方法(get/post/put/delete等)都支持以下常用参数:

参数名类型说明示例
urlstr请求的URL地址(必需)'https://api.example.com'
paramsdictURL查询参数字典{'key1': 'value1', 'key2': 'value2'}
datadict/str/bytes请求体数据,用于POST/PUT{'username': 'admin'}
jsondict自动序列化为JSON的请求体{'name': 'John', 'age': 30}
headersdict自定义HTTP请求头{'User-Agent': 'my-app/1.0'}
cookiesdict要发送的Cookie字典{'session_id': '12345'}
filesdict文件上传字典{'file': open('data.txt', 'rb')}
authtuple基本认证凭据('username', 'password')
timeoutfloat/tuple请求超时时间(秒)5.0(3.0, 7.0)
allow_redirectsbool是否允许重定向True/False
proxiesdict代理服务器设置{'http': 'http://proxy.example.com'}
verifybool/strSSL证书验证True/False或CA证书路径
streambool是否流式传输响应True/False

3 基本使用方法

1. 发送GET请求(使用多个参数)

import requests

# 使用多个参数发送GET请求
response = requests.get(
    url='https://api.example.com/data',
    params={'page': 1, 'limit': 20},
    headers={'Authorization': 'Bearer token123'},
    timeout=5
)

print(response.json())

2. 发送POST请求(多种数据格式)

import requests

# 表单格式提交
response1 = requests.post(
    'https://api.example.com/login',
    data={'username': 'admin', 'password': '123456'}
)

# JSON格式提交
response2 = requests.post(
    'https://api.example.com/users',
    json={'name': 'John', 'age': 30},
    headers={'Content-Type': 'application/json'}
)

# 文件上传
response3 = requests.post(
    'https://api.example.com/upload',
    files={'file': open('report.pdf', 'rb')}
)

Python常用库之requests:让HTTP请求变得简单

requests是Python中最受欢迎的HTTP库之一,它让发送HTTP/1.1请求变得异常简单。相比Python内置的urllib库,requests提供了更简洁、更人性化的API,大大简化了与Web服务交互的过程。

4、实际应用场景

1. Web爬虫

requests常被用于编写简单的网络爬虫。

import requests
from bs4 import BeautifulSoup

# 获取网页内容
response = requests.get('https://news.ycombinator.com')
soup = BeautifulSoup(response.text, 'html.parser')

# 提取新闻标题
for link in soup.select('.titleline > a'):
    print(link.text, link['href'])

2. API交互

与RESTful API交互是requests的常见用途。

import requests

# 获取GitHub用户信息
response = requests.get('https://api.github.com/users/octocat')
user_data = response.json()

print(f"用户名: {user_data['login']}")
print(f"注册时间: {user_data['created_at']}")
print(f"个人简介: {user_data['bio']}")

3. 文件上传

使用requests可以轻松实现文件上传功能。

import requests

# 准备要上传的文件
files = {'file': open('report.xls', 'rb')}

# 发送文件
response = requests.post('https://httpbin.org/post', files=files)

print(response.json())

4. 下载文件

requests可以方便地下载网络资源。

import requests

# 下载图片
url = 'https://www.python.org/static/img/python-logo.png'
response = requests.get(url)

# 保存到本地
with open('python-logo.png', 'wb') as f:
    f.write(response.content)

print("图片下载完成")

5. 身份验证

requests支持多种身份验证方式。

import requests
from requests.auth import HTTPBasicAuth

# 基本认证
response = requests.get('https://api.github.com/user', 
                      auth=HTTPBasicAuth('username', 'password'))

# 更简洁的写法
response = requests.get('https://api.github.com/user', 
                       auth=('username', 'password'))

print(response.json())

6. 代理设置

通过代理服务器发送请求。

import requests

proxies = {
    'http': 'http://10.10.1.10:3128',
    'https': 'http://10.10.1.10:1080',
}

response = requests.get('https://www.example.com', proxies=proxies)

5、错误处理

合理的错误处理是网络请求中必不可少的。

import requests
from requests.exceptions import RequestException

try:
    response = requests.get('https://www.example.com', timeout=5)
    response.raise_for_status()  # 如果状态码不是200,抛出HTTPError异常
    
    # 处理响应内容
    print(response.text)
    
except RequestException as e:
    print(f"请求出错: {e}")

6、高级特性

1. 流式请求

处理大文件时,可以使用流式传输。

import requests

# 流式下载大文件
url = 'https://example.com/large-file.zip'
with requests.get(url, stream=True) as r:
    with open('large-file.zip', 'wb') as f:
        for chunk in r.iter_content(chunk_size=8192): 
            f.write(chunk)

2. 超时设置

为请求设置超时时间,避免长时间等待。

import requests

try:
    # 连接超时3秒,读取超时7秒
    response = requests.get('https://www.example.com', timeout=(3, 7))
except requests.exceptions.Timeout:
    print("请求超时")

3. SSL证书验证

requests默认会验证SSL证书,但也可以禁用。

import requests

# 禁用SSL验证(不推荐生产环境使用)
response = requests.get('https://example.com', verify=False)

# 使用自定义CA证书
response = requests.get('https://example.com', verify='/path/to/cert.pem')

7、性能优化

1. 连接池

requests使用urllib3的连接池,自动保持连接复用。

import requests

# 多次请求会自动复用连接
for i in range(5):
    requests.get('https://www.example.com')

2. 使用Session

对于需要多次请求同一主机的场景,使用Session可以显著提升性能。

import requests

# 创建会话
s = requests.Session()

# 所有请求都会复用TCP连接
for i in range(5):
    s.get('https://www.example.com')

8、总结

requests库以其简洁的API设计、丰富的功能和良好的性能,成为Python开发者处理HTTP请求的首选工具。无论是简单的网页抓取、API交互,还是复杂的文件上传下载、会话管理,requests都能提供优雅的解决方案。

记住,虽然requests使用简单,但在生产环境中使用时仍需注意:

  • 合理的错误处理
  • 适当的超时设置
  • 连接复用(使用Session)
  • 资源释放(使用with语句或手动关闭响应)

掌握了requests库,你就拥有了与Web世界交互的强大工具,能够轻松应对各种网络编程需求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值