You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用requests调用opendota API时出现AttributeError: module 'requests' has no attribute 'ok'

错误原因及修正方案

错误核心原因

你代码里犯了两个关键错误:

  • requests.ok是错误用法:ok是requests.get()返回的Response响应对象的属性,不是requests模块本身的属性。
  • 未保存请求响应对象:调用requests.get()后直接丢弃了返回结果,后续的requests.json()同样错误,因为**json()是Response对象的方法**,不是模块方法。

修正后的完整代码

import requests, json, time, os

# 确保download目录存在,避免文件写入失败
if not os.path.exists("download"):
    os.makedirs("download")

# Download games
def get_match_by_id(match_id):
    m_id = str(match_id)
    # 保存请求响应对象到变量
    response = requests.get(f"https://api.opendota.com/api/matches/{m_id}")
    # 使用响应对象的ok属性判断请求是否成功
    if response.ok:
        print("GET:", m_id)
        # 使用响应对象的json()方法解析数据
        data = response.json()
        # 保存数据到文件
        file_path = os.path.join("download", f"{m_id}_data.json")
        with open(file_path, 'w', encoding='utf-8') as file:
            json.dump(data, file, ensure_ascii=False, indent=2)
    else:
        print(f"请求失败,match_id: {m_id},状态码: {response.status_code}")

match_id = 6757193237  # 保留最后一次赋值的match_id
for i in range(0, 5000):
    get_match_by_id(match_id)
    match_id += 1  # 循环中递增match_id,避免重复请求同一ID
    time.sleep(2)

额外优化说明

  • 增加目录检查:自动创建download目录,避免因目录不存在导致的写入错误
  • 使用os.path.join()拼接路径:比手动拼接更适配不同操作系统
  • 使用with open上下文管理器:自动关闭文件,代码更安全简洁
  • 增加请求失败提示:便于排查请求异常问题
  • 修复循环逻辑:原代码未递增match_id,会重复请求同一比赛ID

内容的提问来源于stack exchange,提问作者user18377332

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 18:45:50