'Failed geolocalization with Geopy, Nominatim: TypeError: 'NoneType' object is not subscriptable

I am trying to use module Geopy, function Nominatim to geolocalize a list of addresses (contained inside a CSV file). Here is my code:

import pandas as pd

from geopy.geocoders import Nominatim 

df = pd.read_csv('incidenti genova 3.csv', delimiter=';', error_bad_lines=False)
indirizzi = df.descrizione_strada

nom=Nominatim(user_agent="my-application") 

coordinate=[]

for element in indirizzi:
    print(element)
    target1=nom.geocode(element)[1]
    print(target1)
    coordinate.append(target1)

When I run it, it prints the first address of my list, then I get this error:

TypeError                                 
Traceback (most recent call last)<br> <ipython-input-9-765a06164536> in <module>()<br>
     13     print(element)<br>
     14 <br>
---> 15     target1=nom.geocode(element)[1]<br>
     16     print(target1)<br>
     17     coordinate.append(target1)<br>

TypeError: 'NoneType' object is not subscriptable

I found out it means that it failed geolocalizing the address because the address is not complete enough. What I want is the code to skip the elements of the list it could not geolocalize and go on printing the others.

How can I do it?



Solution 1:[1]

Well you are missing one of the very important fundamentals of coding, i.e the try... except statements

You probably wanna do something like this:

for element in indirizzi:
  try: 
   print(element)
   target1=nom.geocode(element)[1]
   print(target1)
   coordinate.append(target1)
  except NoneType:
   pass

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Tms91