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

使用Requests爬取店铺数据接口时出现TypeError问题求助

解决方案

问题根源

你当前代码遍历的是整个JSON响应的键值对,但接口返回的结构中,并非所有value都是店铺字典——比如可能包含状态标识类的字段(如success),这类字段的value是字符串/布尔值,尝试对其使用字典索引['id']就会触发TypeError: string indices must be integers。真正的店铺数据是嵌套在响应的某个子列表中(比如stores字段)。

修正后的代码

import requests

url = 'https://storelocator.apps.isenselabs.com/stores/getStoresData?shop=puntadelcielo-1658.myshopify.com&sa=0'

r = requests.get(url)
data = r.json()

# 提取店铺列表,使用get方法避免字段不存在时抛出KeyError
stores_list = data.get('stores', [])
for store in stores_list:
    print("Store ID:", store['id'])
    print("Name:", store['name'])
    print("Address:", store['store_address'])
    print("Latitude:", store['latitude'])
    print("Longitude:", store['longitude'])
    print("-" * 30)  # 分隔不同店铺数据,提升可读性

说明

  1. 先通过data.get('stores', [])精准定位到存储店铺数据的列表,第二个参数[]确保即便stores字段不存在,代码也不会报错,而是返回空列表。
  2. 直接遍历店铺列表中的每个字典项,此时每个store都是包含店铺信息的字典,可以正常使用['id']等索引获取对应字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 04:12:40