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

调用Nominatim获取城市坐标报AttributeError: 'NoneType'无'longitude'属性

问题根因

你遇到的报错本质是 geolocator.geocode(city) 无法匹配到对应城市的坐标时,会返回 None,你没有对该返回结果做校验,直接调用 None 的 longitude 属性触发了属性不存在错误。哪怕你确认城市名不含数字,也可能因为城市名拼写不规范、Nominatim数据库未收录、接口请求触发速率限制等原因返回空结果。

修复后代码

首先记得导入依赖模块:

import time
from geopy.geocoders import Nominatim

def get_coordinates(city_list):
    """接收城市列表,返回城市与对应经纬度的字典"""
    geolocator = Nominatim(user_agent='location script')
    dicto = {}
    fail_list = []

    for city in city_list:
        try:
            location = geolocator.geocode(city)
            # 符合Nominatim免费接口的速率限制要求,避免频繁请求被拒
            time.sleep(1)
        except Exception as e:
            print(f"请求城市{city}时发生异常:{e}")
            fail_list.append(city)
            continue
        
        # 对返回结果做非空校验
        if location:
            coordinate_values = (location.longitude, location.latitude)
            dicto[city] = coordinate_values
        else:
            print(f"未匹配到城市{city}的坐标")
            fail_list.append(city)
    
    print(f"坐标获取完成,共有{len(fail_list)}个城市匹配失败,列表:{fail_list}")
    return dicto

核心调整点

  • 新增返回结果非空校验,匹配失败的城市不会触发程序崩溃,会单独打印提示并汇总到失败列表,可后续单独处理这些异常城市
  • 新增1秒请求间隔,符合Nominatim公开接口的调用规则,避免因速率限制导致大量匹配失败
  • 优化异常捕获逻辑,不会笼统抛出全局异常,会保留原始错误信息方便排查问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:36:05