如何用Python提取火币API标题并检测变更?解决列表索引错误
解决列表索引错误并实现标题变更检测
错误原因分析
你碰到的TypeError: list indices must be integers or slices, not str,本质是因为接口返回的data.items是一个列表类型(里面装着多个公告条目),而不是单个字典。你直接用['title']去访问列表,自然会报错——列表只能用数字索引(比如[0]取第一个元素)或者切片来操作。
修正后的完整代码
下面是调整后的代码,不仅修复了索引错误,还完善了标题变更检测的逻辑:
import requests import json # 接口地址 API_URL = "https://www.huobi.com/p/api/contents/" def get_current_titles(): """从接口获取当前所有公告标题""" try: response = requests.get(API_URL) response.raise_for_status() # 捕获HTTP请求错误 data = response.json() # items是列表,遍历每个元素提取title return [item['title'] for item in data['data']['items']] except Exception as e: print(f"获取当前标题失败: {str(e)}") return [] def check_title_changes(): """检测标题是否发生变更""" # 读取历史标题 try: with open('notice.json', 'r') as f: historical_titles = json.load(f) except (IOError, json.JSONDecodeError): # 文件不存在或解析失败,初始化空列表 historical_titles = [] # 获取当前标题 current_titles = get_current_titles() if not current_titles: return # 对比差异 new_titles = [title for title in current_titles if title not in historical_titles] removed_titles = [title for title in historical_titles if title not in current_titles] # 输出变更信息 if new_titles: print("新增标题:") for title in new_titles: print(f"- {title}") if removed_titles: print("移除的标题:") for title in removed_titles: print(f"- {title}") if not new_titles and not removed_titles: print("标题未发生变更") # 保存最新标题到文件 try: with open('notice.json', 'w') as f: json.dump(current_titles, f, ensure_ascii=False, indent=2) except Exception as e: print(f"保存标题失败: {str(e)}") if __name__ == "__main__": check_title_changes()
关键修改点说明
- 列表遍历提取标题:用列表推导式
[item['title'] for item in data['data']['items']]遍历items列表,逐个取出每个条目的title字段,得到所有标题的列表。 - 完善异常处理:新增了HTTP请求错误捕获、JSON解析错误捕获,避免程序因为接口异常直接崩溃。
- 变更检测逻辑:通过集合对比,找出新增和移除的标题,清晰展示变更内容。
- 规范文件读写:保存时指定
ensure_ascii=False,避免中文标题出现乱码,indent=2让JSON文件更易读。
内容的提问来源于stack exchange,提问作者ssithuxx
相关产品推荐
相关产品推荐

