已解决!geopy geocoders 运行代码块报错问题。
from geopy.geocoders import Nominatim
# 初始化api
geolocator = Nominatim(user_agent="my-application")
# 邮编
place = "40.056793 116.305811"
location = geolocator.reverse(place) # 纬度在前,经度在后
# 获得数据
data = location.raw
print(data)
loc_data = data['display_name'].split()
print("Full Location:", loc_data)
print("Zip code : ", loc_data[-2])
出现报错: geopy.exc.ConfigurationError: Using Nominatim with default or sample user_agent
“geopy/2.4.1” is strongly discouraged, as it violates Nominatim’s ToS https://operations.osmfoundation.org/policies/nominatim/ and may possibly cause 403 and 429 HTTP errors. Please specify a custom user_agent
with Nominatim(user_agent="my-application")
or by overriding the default user_agent
: geopy.geocoders.options.default_user_agent = "my-application"
.
解决方法: 打开 anaconda 路径下文件:anaconda\envs\python38\Lib\site-packages\geopy\geocoders\nominatim.py
(Add a # before each line in raise ConfigurationError( … ) , and add a line that says pass right above.)
第105行修改为,注释掉raise ConfigurationError( … ),改为pass。
if (self.domain == _DEFAULT_NOMINATIM_DOMAIN
and self.headers['User-Agent'] in _REJECTED_USER_AGENTS):
pass
# raise ConfigurationError(
# 'Using Nominatim with default or sample `user_agent` "%s" is '
# 'strongly discouraged, as it violates Nominatim\'s ToS '
# 'https://operations.osmfoundation.org/policies/nominatim/ '
# 'and may possibly cause 403 and 429 HTTP errors. '
# 'Please specify a custom `user_agent` with '
# '`Nominatim(user_agent="my-application")` or by '
# 'overriding the default `user_agent`: '
# '`geopy.geocoders.options.default_user_agent = "my-application"`.'
# % self.headers['User-Agent']
# )
即可运行成功:
{'place_id': 194340070, 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. http://osm.org/copyright', 'osm_type': 'way', 'osm_id': 1186225518, 'lat': '40.056787094612076', 'lon': '116.30581209681867', 'class': 'highway', 'type': 'secondary', 'place_rank': 26, 'importance': 0.10000999999999993, 'addresstype': 'road', 'name': '西二旗北路', 'display_name': '西二旗北路, 海淀区, 北京市, 102208, 中国', 'address': {'road': '西二旗北路', 'city': '海淀区', 'state': '北京市', 'ISO3166-2-lvl4': 'CN-BJ', 'postcode': '102208', 'country': '中国', 'country_code': 'cn'}, 'boundingbox': ['40.0567774', '40.0601057', '116.3057599', '116.3174453']}
Full Location: ['西二旗北路,', '海淀区,', '北京市,', '102208,', '中国']
Zip code : 102208,