error (429) Too Many Requests while geocoding with geopy in Python

梦想的初衷 提交于 2019-11-29 11:01:39

geopy since 1.16.0 includes a RateLimiter class which provides a convenient way to deal with the Too Many Requests 429 error by adding delays between the queries and retrying the failed requests.

from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="specify_your_app_name_here")

from geopy.extra.rate_limiter import RateLimiter
geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)

df['coord'] = df['address'].apply(geocode).apply(lambda location: (location.latitude, location.longitude))
df.head()

Docs: https://geopy.readthedocs.io/en/1.16.0/#usage-with-pandas

I would imagine you use a for loop. Without seeing your data, it would look something like this.

x = df['address'].tolist()
names = []

for item in x:
    d={}
    a = geolocator.geocode(item, exactly_one=True, timeout=60)
    try:
        d["Latitude"] = a.latitude
    except:
        pass
    try:
        d["Longitude"] = a.longitude
    except:
        pass
    time.sleep(2)
    names.append(d)

d

This is how you would implement sleep to wait 2 seconds before running the loop again. Also, in the event that the geolocator cannot find the latitude and longitude, it will pass instead of exiting out of the loop and having you start over.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!