Python(7)----小作业之模拟访问+错误总结

API请求与数据分析任务总结文档

📋 任务概述

任务目标

使用Python的requests库向公共API发送请求,分析返回的数据结构,并实现完整的异常处理。

使用API

  • API地址: https://jsonplaceholder.typicode.com/posts
  • 类型: RESTful API
  • 方法: GET
  • 返回格式: JSON

🔧 代码实现与问题总结

初始代码问题分析

主要错误:类型理解错误

# 错误代码
for k in content_response.items['title']:
    print(f'标题:{k}')

问题根源:

  1. 数据结构误解: 没有正确理解response.json()返回的是列表,不是字典
  2. 方法使用错误: 对列表使用了字典的items()方法
  3. 语法错误: items['title']语法不正确

正确理解:

# response.json() 返回的数据结构:
[
    {
        "userId": 1,
        "id": 1,
        "title": "帖子标题",
        "body": "帖子内容"
    },
    {
        "userId": 1,
        "id": 2,
        "title": "另一个标题",
        "body": "另一个内容"
    },
    # ... 更多帖子
]

修复后的正确代码

print(f'获取所有帖子的标题:')
for post in content_response:  # post是字典,不是k
    print(f'标题:{post.get("title", "")}')  # 使用get方法安全访问

🎯 关键知识点总结

1. 请求发送与异常处理

import requests
from requests.exceptions import ConnectionError, HTTPError, Timeout

try:
    response = requests.get(url=url, timeout=10)  # 添加超时
    response.raise_for_status()  # 自动检查HTTP状态码
    # 处理成功响应...
    
except HTTPError as e:
    print(f'HTTP错误: {e}')
except ConnectionError as e:
    print(f'连接错误: {e}')
except Timeout as e:
    print(f'请求超时: {e}')
except Exception as e:
    print(f'其他异常: {e}')

要点:

  • 使用分层异常处理,从具体到一般
  • response.raise_for_status()自动检查4xx/5xx错误
  • 设置timeout避免无限等待

2. 响应数据分析

# 获取响应状态
print(f'状态码: {response.status_code}')

# 解析JSON数据
content_response = response.json()  # 返回的是列表!

# 数据结构分析
print(f'数据总量: {len(content_response)}')  # 列表长度

# 访问单个元素
first_post = content_response[0]  # 第一个帖子(字典)
print('第一个帖子详情:')
for key, value in first_post.items():  # 遍历字典
    print(f'{key}: {value}')

# 提取特定字段
print('所有帖子标题:')
for post in content_response:  # 遍历列表
    title = post.get('title', '无标题')  # 安全获取
    print(f'标题: {title}')

3. 数据结构理解

response.json()
    ↓
列表 (List)
    ↓
[字典1, 字典2, 字典3, ...]
    ↓
每个字典包含: userId, id, title, body

🛠️ 常见错误与解决方案

错误1: 混淆列表和字典操作

错误: list.items()
解决: 列表没有items()方法,字典才有

错误2: 错误的遍历方式

错误: for k in list.items['key']
解决:

# 正确方式1
for item in list:
    value = item['key']
    
# 正确方式2(安全)
for item in list:
    value = item.get('key', '默认值')

错误3: 缺少错误处理

错误: 直接访问不存在的键
解决: 使用dict.get(key, default)方法

错误4: 字符串引号嵌套

错误: print(f'标题:{k.get('title',' ')}')
解决: 使用双引号或转义

print(f"标题:{k.get('title', ' ')}")  # 外双内单

📊 数据分析技巧

1. 数据统计

# 基本统计
total_posts = len(content_response)
print(f'帖子总数: {total_posts}')

# 按用户分组
from collections import defaultdict
user_posts = defaultdict(int)
for post in content_response:
    user_posts[post['userId']] += 1

print('各用户发帖数:')
for user_id, count in user_posts.items():
    print(f'用户 {user_id}: {count} 篇')

2. 数据采样

# 查看前N个样本
sample_size = 3
print(f'前{sample_size}个帖子:')
for i, post in enumerate(content_response[:sample_size]):
    print(f'{i+1}. {post["title"]}')

3. 字段分析

# 分析所有可用字段
if content_response:
    sample_post = content_response[0]
    print('可用字段:')
    for field in sample_post.keys():
        print(f'- {field}')

🔍 调试技巧

1. 类型检查

print(f'响应类型: {type(response.json())}')
print(f'第一个元素类型: {type(content_response[0])}')

2. 数据结构探索

# 查看数据结构
import json
print('完整数据结构:')
print(json.dumps(content_response[0], indent=2, ensure_ascii=False))

3. 逐步调试

# 分步处理,避免一次性操作太多
data = response.json()
print(f"步骤1 - 获取数据,类型: {type(data)}, 长度: {len(data)}")

first_item = data[0] if data else {}
print(f"步骤2 - 第一个元素类型: {type(first_item)}")

if first_item:
    print(f"步骤3 - 可用键: {list(first_item.keys())}")

📈 学习收获

已掌握技能

  1. 请求发送: 使用requests库发送HTTP请求
  2. 异常处理: 分层处理各种网络异常
  3. 数据解析: 解析JSON响应数据
  4. 数据结构分析: 理解列表和字典的嵌套结构
  5. 安全访问: 使用get()方法避免KeyError
  6. 数据遍历: 正确遍历复杂数据结构

需要继续加强

  1. 🔄 类型判断: 在处理数据前确认数据类型
  2. 🔄 错误预防: 添加更多边界条件检查
  3. 🔄 代码优化: 提高代码的可读性和复用性

🎯 后续练习建议

基础巩固

  1. 尝试其他API端点(如 /users, /comments
  2. 添加参数发送请求(如 ?userId=1
  3. 实现数据过滤和搜索功能

进阶挑战

  1. 封装为可复用的函数或类
  2. 添加日志记录功能
  3. 实现数据持久化(保存到文件)
  4. 添加单元测试

这份总结文档涵盖了任务的核心知识点和常见问题,建议定期回顾并结合实际项目练习,以巩固所学内容。

posted @ 2025-10-31 22:49  CalvinMax  阅读(5)  评论(0)    收藏  举报