本文目录导读:

我来为你介绍Python发送GET请求的几种常见方法:
使用requests库(最常用)
首先安装requests库:
pip install requests
基本GET请求
import requests
# 发送GET请求
response = requests.get('https://api.github.com')
# 检查状态码
print(f"状态码: {response.status_code}")
# 获取响应内容
print(f"响应内容: {response.text}")
# 解析JSON响应
data = response.json()
print(f"JSON数据: {data}")
带参数的GET请求
import requests
# 方法1:直接在URL中带参数
response = requests.get('https://httpbin.org/get?name=张三&age=25')
# 方法2:使用params参数
params = {
'name': '张三',
'age': 25,
'city': '北京'
}
response = requests.get('https://httpbin.org/get', params=params)
print(response.url) # 查看实际请求的URL
print(response.json())
带请求头的GET请求
import requests
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
'Accept': 'application/json',
'Authorization': 'Bearer your_token_here' # 如果有认证需要
}
response = requests.get('https://api.github.com', headers=headers)
print(response.json())
超时和异常处理
import requests
from requests.exceptions import Timeout, RequestException
try:
# 设置超时时间为5秒
response = requests.get('https://api.github.com', timeout=5)
response.raise_for_status() # 检查HTTP错误
if response.status_code == 200:
data = response.json()
print("请求成功:", data)
except Timeout:
print("请求超时")
except RequestException as e:
print(f"请求失败: {e}")
使用urllib库(Python内置)
from urllib import request, parse
import json
# 带参数的GET请求
params = {
'name': '张三',
'age': 25
}
query_string = parse.urlencode(params)
url = f'https://httpbin.org/get?{query_string}'
# 发送请求
req = request.Request(url)
req.add_header('User-Agent', 'Mozilla/5.0')
try:
with request.urlopen(req, timeout=5) as response:
# 读取响应内容
data = response.read().decode('utf-8')
print(f"状态码: {response.status}")
print(f"响应内容: {data}")
# 解析JSON
json_data = json.loads(data)
print(f"JSON数据: {json_data}")
except Exception as e:
print(f"请求失败: {e}")
使用aiohttp库(异步请求)
import aiohttp
import asyncio
async def fetch_data(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
return await response.json()
async def main():
# 发送单个请求
data = await fetch_data('https://api.github.com')
print(data)
# 并发发送多个请求
urls = [
'https://api.github.com',
'https://httpbin.org/get',
'https://jsonplaceholder.typicode.com/posts/1'
]
tasks = [fetch_data(url) for url in urls]
results = await asyncio.gather(*tasks)
for url, result in zip(urls, results):
print(f"{url}: {result}")
# 运行异步代码
asyncio.run(main())
完整示例:天气API请求
import requests
import json
def get_weather(city_code='101010100'):
"""
获取天气信息
:param city_code: 城市代码,默认北京
"""
url = f'http://www.weather.com.cn/data/cityinfo/{city_code}.html'
try:
# 设置请求头模拟浏览器
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
# 发送GET请求
response = requests.get(url, headers=headers, timeout=5)
response.raise_for_status()
# 解析JSON数据
weather_data = response.json()
# 提取有用信息
if weather_data.get('weatherinfo'):
info = weather_data['weatherinfo']
print(f"城市: {info.get('city')}")
print(f"最高温度: {info.get('temp2')}℃")
print(f"最低温度: {info.get('temp1')}℃")
print(f"天气: {info.get('weather')}")
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
except json.JSONDecodeError:
print("JSON解析失败")
except KeyError as e:
print(f"数据格式错误: {e}")
# 调用函数
get_weather('101010100') # 北京天气
实用技巧
会话保持
import requests
# 使用Session对象可以保持cookies
session = requests.Session()
# 第一次请求可能设置cookies
session.get('https://example.com/login')
# 后续请求会自动携带cookies
response = session.get('https://example.com/profile')
重定向处理
import requests
# 禁止自动重定向
response = requests.get('https://httpbin.org/redirect/1', allow_redirects=False)
print(f"状态码: {response.status_code}") # 302
print(f"重定向URL: {response.headers.get('Location')}")
推荐使用方式:
- 日常开发:
requests库(简单易用) - 性能要求高:
aiohttp(异步) - 不需要第三方库:
urllib(内置)
选择哪种方式主要看你的具体需求和项目环境。
版权声明:NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
CBA直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播
英超直播