You need to enable JavaScript to run this app. Postman获取麦当劳门店数据解析报KeyError无法导出Excel如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Postman获取麦当劳门店数据解析报KeyError无法导出Excel如何解决

错误原因

你对问题的猜测完全正确。该接口返回的features数组下的每个门店对象,所有地址、电话等业务字段均嵌套在properties子节点中,你直接从store根节点读取字段自然不存在,因此抛出KeyError。
完整的单条门店数据结构参考如下:

{
  "type": "Feature",
  "properties": {
    "addressLine1": "xxx",
    "addressLine2": "xxx",
    // 其他你需要的字段都在这层
  },
  "geometry": {
    // 坐标相关信息
  }
}

修正后代码

你只需要修改循环部分的字段读取逻辑,同时可以用字典get方法增加容错,避免个别门店缺字段导致程序直接中断:

import requests
import csv
import json

url = "https://www.mcdonalds.com/googleapps/GoogleRestaurantLocAction.do?method=searchLocation&latitude=43.6936965&longitude=-79.2969938&radius=1000000&maxResults=1700&country=ca&language=en-ca&showClosed=&hours24Text=Open%2024%20hr"

payload={}
files={}
headers = {
  'authority': 'www.mcdonalds.com',
  'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"',
  'accept': '*/*',
  'x-requested-with': 'XMLHttpRequest',
  'sec-ch-ua-mobile': '?0',
  'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.106 Safari/537.36',
  'sec-fetch-site': 'same-origin',
  'sec-fetch-mode': 'cors',
  'sec-fetch-dest': 'empty',
  'referer': 'https://www.mcdonalds.com/ca/en-ca/restaurant-locator.html',
  'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8',
  'cookie': '替换为你自己的有效cookie',
  'dnt': '1'
} 

response = requests.request("GET", url, headers = headers, data = payload, files = files)
stores = json.loads(response.text)

with open('Mcdonlocation.csv', mode='w', encoding='utf-8-sig') as CSVFile:
    writer = csv.writer(CSVFile, delimiter=",", quotechar='"', quoting=csv.QUOTE_MINIMAL)
    writer.writerow([
        "addressLine1",
        "addressLine2",
        "addressLine3",
        "subDivision",
        "postcode",
        "telephone"
        ])

    for store in stores['features']:
        # 先取properties子节点
        store_info = store.get('properties', {})
        row = [
            store_info.get("addressLine1", ""),
            store_info.get("addressLine2", ""),
            store_info.get("addressLine3", ""),
            store_info.get("subDivision", ""),
            store_info.get("postcode", ""),
            store_info.get("telephone", "")
        ]
        writer.writerow(row)

注:代码里加了encoding='utf-8-sig'是为了保证导出的CSV用Excel打开不会乱码,cookie记得替换成你自己当前的有效cookie,避免接口鉴权失败返回空数据。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 04:24:02