使用Python库追踪经纬度遇ArcGIS超时问题求最佳实践
地理编码批量处理最佳实践
针对你用ArcGIS Geocoder处理2800条地址时出现的超时中断、仅获取部分结果的问题,以下是实用的优化方案:
添加请求间隔,避免触发限流
免费地理编码服务普遍有请求频率限制,短时间内大量请求会被服务器拒绝或超时。在每次请求后添加1-2秒的间隔,给服务器缓冲时间:import time # 循环内添加 time.sleep(1)延长超时时间
默认的1秒超时太短,容易因网络波动导致请求失败。初始化Geolocator时设置更长的超时值(比如10秒):geolocator = ArcGIS(timeout=10)加入异常处理,防止程序中断
捕获超时、地址无法解析等异常,跳过失败条目并记录,保证程序能跑完所有地址,后续还能处理失败的部分:for address in new_wordlist: try: location = geolocator.geocode(address) if location: # 确认地址能被解析 loc={'latitude':location.latitude,'longitude':location.longitude} lat_long.append(loc) else: # 记录无法解析的地址 lat_long.append({'address': address, 'error': '无法解析'}) except Exception as e: # 记录超时或其他错误 lat_long.append({'address': address, 'error': str(e)}) time.sleep(1)分批保存中间结果
每处理一定数量的地址(比如100条)就保存一次数据,避免程序崩溃导致之前的结果丢失:import pandas as pd # 循环内加入判断 if len(lat_long) % 100 == 0: pd.DataFrame(lat_long).to_csv('geocode_results_temp.csv', index=False) # 全部处理完后再保存最终结果 pd.DataFrame(lat_long).to_csv('geocode_final_results.csv', index=False)使用本地缓存减少重复请求
如果地址列表中有重复条目,用字典缓存已解析的结果,避免重复请求服务器:cache = {} for address in new_wordlist: if address in cache: lat_long.append(cache[address]) continue # 后续请求逻辑... if location: loc = {'latitude': location.latitude, 'longitude': location.longitude} cache[address] = loc lat_long.append(loc)
整合后的完整示例代码:
lat_long = [] cache = {} import time import pandas as pd from geopy.geocoders import ArcGIS # 初始化地理编码器,设置超时 geolocator = ArcGIS(timeout=10) for idx, address in enumerate(new_wordlist, 1): # 检查缓存 if address in cache: lat_long.append(cache[address]) continue try: location = geolocator.geocode(address) if location: loc = {'latitude': location.latitude, 'longitude': location.longitude} cache[address] = loc lat_long.append(loc) else: lat_long.append({'address': address, 'error': '地址无法解析'}) except Exception as e: lat_long.append({'address': address, 'error': str(e)}) # 添加请求间隔 time.sleep(1) # 每100条保存一次中间结果 if idx % 100 == 0: pd.DataFrame(lat_long).to_csv(f'geocode_temp_{idx}.csv', index=False) print(f"已处理{idx}条,保存中间结果") # 保存最终结果 pd.DataFrame(lat_long).to_csv('geocode_final_results.csv', index=False) print("全部处理完成")
内容的提问来源于stack exchange,提问作者Amrutha
相关产品推荐
相关产品推荐

