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

AttributeError: 'bytes'对象无'get'属性问题排查求助

问题分析:AttributeError 'bytes' object has no attribute 'get'

问题场景

调用API时触发AttributeError 'bytes' object has no attribute 'get',错误出现在代码行'name': alert.get('hostname')。

原代码

import requests
from requests.auth import HTTPBasicAuth

incidents = []
limit = 100
offset = 0
got_all_events = False
while not got_all_events:
    alerts = requests.get(f'***', auth=HTTPBasicAuth('***', '***'))
    print(alerts)
    for alert in alerts:
        incident = { 
            'name': alert.get('hostname'),
            'rawJSON': json.dumps(alert),
        }
        incidents.append(incident)
    if len(alerts) == limit:
        offset += limit
    else:
        got_all_events = True

print(incident)

API返回结构

{
  "totalSize": 0,
  "data": [
    {
      "hostname": "string",
      "domain": "string",
      "tags": "string",
      "os": {}
    }
  ],
  "size": 0
}

错误原因

  1. 未解析API响应:requests.get()返回的是Response对象,直接遍历这个对象会逐字节迭代,导致alert是bytes类型,自然没有get()方法。
  2. 未提取正确数据字段:API返回的实际数据嵌套在data数组里,原代码没有针对这个结构做处理。
  3. 缺失模块导入:代码中使用了json.dumps()但没导入json模块。
  4. 参数未传递:定义了offset变量但没在请求URL中使用,无法实现分页拉取数据。
  5. 变量名错误:最后打印的incident是循环内的局部变量,应该打印incidents列表。

修复方案

  1. 用response.json()解析API返回的JSON数据,得到字典结构。
  2. 从解析后的字典中取出data字段的数组进行遍历。
  3. 补充导入json模块。
  4. 在请求URL中加入offset和limit参数,实现分页逻辑。
  5. 修正最后打印的变量为incidents。

修正后的完整代码

import requests
import json
from requests.auth import HTTPBasicAuth

incidents = []
limit = 100
offset = 0
got_all_events = False
while not got_all_events:
    # 在URL中加入分页参数,替换***为实际API地址
    alerts_response = requests.get(
        f'***?limit={limit}&offset={offset}', 
        auth=HTTPBasicAuth('***', '***')
    )
    # 解析JSON响应
    alerts_data = alerts_response.json()
    # 遍历data数组中的告警数据
    for alert in alerts_data['data']:
        incident = { 
            'name': alert.get('hostname'),
            'rawJSON': json.dumps(alert),
        }
        incidents.append(incident)
    # 根据返回的size判断是否还有更多数据
    if alerts_data['size'] == limit:
        offset += limit
    else:
        got_all_events = True

print(incidents)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 10:55:17