掌握Python中最常用的HTTP请求库
Requests是Python中最流行的HTTP库,它让HTTP请求变得简单易用。就像浏览器访问网页一样, 我们可以用Requests获取网页内容,但它是通过编程方式实现的。
# 安装requests
pip install requests
# 基础使用
import requests
response = requests.get('https://example.com')
print(response.text) # 获取网页内容
GET请求用于从服务器获取数据,这是最常见的HTTP请求方法。 当你在浏览器中输入网址并按回车,就是发送了一个GET请求。
# 最简单的GET请求
import requests
response = requests.get('https://www.example.com')
print(f"状态码: {response.status_code}")
print(f"响应内容类型: {response.headers['content-type']}")
print(f"编码: {response.encoding}")
print(f"内容长度: {len(response.text)}字符")
# 打印前100个字符
print(response.text[:100])
很多时候,我们需要在URL中添加查询参数来获取特定的数据。例如在搜索引擎中搜索关键词, 这些关键词通常会作为查询参数添加到URL中。
# 带查询参数的GET请求
import requests
# 方法1:直接在URL中添加参数
url1 = 'https://www.example.com/search?q=python&page=1'
response1 = requests.get(url1)
# 方法2:使用params参数(推荐)
url2 = 'https://www.example.com/search'
params = {
'q': 'python', # 搜索关键词
'page': 1, # 页码
'sort': 'relevance' # 排序方式
}
response2 = requests.get(url2, params=params)
# 查看最终请求的URL
print(f"最终请求的URL: {response2.url}")
有些网站会检查请求头信息,如果发现是爬虫程序,可能会拒绝提供数据。 因此,我们通常需要设置User-Agent等请求头信息来模拟浏览器访问。
# 设置请求头
import requests
url = 'https://www.example.com'
# 构造请求头字典
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Referer': 'https://www.google.com/' # 模拟从Google搜索过来
}
response = requests.get(url, headers=headers)
# 查看服务器是否接收到请求头
print("请求发送成功!")
下面我们来看一个实际应用案例:通过和风天气API获取指定城市的天气信息。
# GET请求实际案例:获取天气信息
import requests
# 和风天气API示例(注意:实际使用需要申请API密钥)
url = 'https://devapi.qweather.com/v7/weather/now'
params = {
'location': '101010100', # 北京的城市ID
'key': 'YOUR_API_KEY' # 替换为你的API密钥
}
try:
response = requests.get(url, params=params, timeout=10)
# 检查请求是否成功
if response.status_code == 200:
# 解析JSON响应
weather_data = response.json()
# 提取关键信息
if 'now' in weather_data:
now = weather_data['now']
print(f"城市:北京")
print(f"当前温度:{now['temp']}°C")
print(f"天气状况:{now['text']}")
print(f"风向:{now['windDir']} {now['windScale']}级")
print(f"湿度:{now['humidity']}%")
else:
print(f"请求失败,状态码:{response.status_code}")
except Exception as e:
print(f"发生错误:{e}")
POST请求通常用于向服务器提交数据,例如提交表单、上传文件等。与GET请求不同, POST请求的数据通常放在请求体中,而不是URL中。
# 基础POST请求
import requests
url = 'https://www.example.com/login'
# 准备表单数据
form_data = {
'username': 'test_user',
'password': 'test_password'
}
# 发送POST请求
response = requests.post(url, data=form_data)
# 检查登录是否成功
if response.status_code == 200:
print("登录请求发送成功!")
else:
print(f"登录失败,状态码:{response.status_code}")
在现代Web应用中,特别是前后端分离的项目中,经常需要发送JSON格式的数据。 Requests库可以很方便地发送JSON数据。
# 发送JSON数据
import requests
import json
url = 'https://api.example.com/data'
# 准备JSON数据
json_data = {
'name': '张三',
'age': 25,
'email': 'zhangsan@example.com',
'hobbies': ['阅读', '编程', '运动']
}
# 方法1:使用json参数(推荐)
response1 = requests.post(url, json=json_data)
# 方法2:手动设置headers和转换数据
headers = {
'Content-Type': 'application/json'
}
response2 = requests.post(url, data=json.dumps(json_data), headers=headers)
# 查看响应
if response1.status_code == 200:
result = response1.json()
print(f"请求成功,服务器返回:{result}")
POST请求还可以用于上传文件,这在很多Web应用中都很常见,例如上传头像、附件等。
# 文件上传
import requests
url = 'https://api.example.com/upload'
# 准备文件数据
files = {
'file': open('example.txt', 'rb') # 打开文件,rb表示以二进制模式读取
}
# 可以同时发送表单数据
data = {
'description': '这是一个示例文件',
'category': '文档'
}
try:
response = requests.post(url, files=files, data=data)
if response.status_code == 200:
print("文件上传成功!")
else:
print(f"文件上传失败,状态码:{response.status_code}")
except Exception as e:
print(f"文件上传出错:{e}")
finally:
# 确保文件被关闭
if 'file' in locals() or 'file' in globals():
files['file'].close()
下面我们来看一个实际应用案例:通过百度翻译API将中文翻译成英文。
# POST请求实际案例:翻译服务
import requests
import json
# 百度翻译API示例(注意:实际使用需要申请API密钥)
url = 'https://fanyi-api.baidu.com/api/trans/vip/translate'
# 准备请求参数
params = {
'q': '你好,世界!',
'from': 'zh',
'to': 'en',
'appid': 'YOUR_APPID', # 替换为你的AppID
'salt': '123456', # 随机数
'sign': 'SIGN_VALUE' # 签名,需要根据appid、q、salt、密钥计算
}
# 也可以使用POST的data参数
# data = params.copy()
headers = {
'Content-Type': 'application/x-www-form-urlencoded'
}
try:
# 发送GET请求或者POST请求都可以
# response = requests.get(url, params=params)
response = requests.post(url, params=params, headers=headers)
if response.status_code == 200:
result = response.json()
if 'trans_result' in result:
translated_text = result['trans_result'][0]['dst']
print(f"原文:{params['q']}")
print(f"译文:{translated_text}")
else:
print(f"翻译失败:{result}")
else:
print(f"请求失败,状态码:{response.status_code}")
except Exception as e:
print(f"翻译过程中发生错误:{e}")
小华是一名新闻专业的学生,需要收集各大新闻网站的热点新闻进行分析。她发现手动复制粘贴效率太低, 于是决定用Requests库编写一个简单的新闻爬虫。
import requests
from bs4 import BeautifulSoup
# 小华的新闻爬虫
class NewsSpider:
def __init__(self):
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
def get_news(self, url):
try:
response = requests.get(url, headers=self.headers, timeout=10)
if response.status_code == 200:
return response.text
else:
print(f"请求失败,状态码:{response.status_code}")
return None
except Exception as e:
print(f"请求出错:{e}")
return None
# 使用示例
spider = NewsSpider()
content = spider.get_news('https://news.example.com')
print(f"成功获取网页内容,长度:{len(content)}字符")
小华的心得:通过使用Requests库,我可以在几分钟内收集到几百条新闻数据, 这比我手动操作快了100倍!而且代码还能重复使用。
使用requests获取百度首页内容,并打印响应状态码和内容长度。
# 目标:requests.get('https://www.baidu.com')
创建一个函数,为请求添加合适的User-Agent头部信息。
# 提示:headers = {'User-Agent': 'Mozilla/5.0...'}
编写一个带有超时功能的请求函数,避免程序长时间等待。
# 目标:requests.get(url, timeout=5)
完善爬虫程序,添加完整的异常处理机制。
# 提示:try-except捕获网络异常
模拟登录表单提交,学习POST请求的使用方法。
# 目标:requests.post(url, data={'username': 'xxx'})
创建一个函数,检查响应状态码并返回相应的错误信息。
# 提示:检查response.status_code
编写程序批量测试多个URL的访问状态。
# 目标:遍历URL列表,检查每个的响应状态
实现一个带有重试功能的请求函数,提高爬虫稳定性。
# 提示:使用循环实现重试逻辑