Search code examples
pythonbeautifulsoupmechanizedata-extraction

Input data to website and extract result


I'm hoping someone can guide me with this little project.

I have a list of addresses in an excel file and would like to paste the addresses (can be zipcodes) individually into the website linked below and extract the Long/Lat coordinates and paste them next to the address in the same excel file.

Is this possible? I'm assuming I would use a combination of python, beautifulsoup? I read somewhere about mechanize. Your help would be appreciated.

website:https://www.latlong.net/convert-address-to-lat-long.html


Solution

  • The mentioned website uses the Google Maps API to convert an address to coordinates (known as geocoding). To be able to use the Google Maps API, you will need an API key
    You can follow the instructions here on how to obtain an API key.

    Once you have done that you need to install the googlemaps Python package to be able to use the API:
    pip install googlemaps

    The following code converts an address to coordinates and prints out at which coordinates the given address is at:

    import googlemaps
    
    key = 'YOUR_API_KEY'
    address = '1600 Amphitheatre Parkway' #  Google's address
    
    gmaps = googlemaps.Client(key=key)
    
    # Convert the given address to coordinates. You can use gmaps.reverse_geocode((lat, lng)) 
    # to convert the coordinates back to an address
    geocode_result = gmaps.geocode(address)
    
    lat = geocode_result[0]['geometry']['location']['lat'] #  Get the latitude
    lng = geocode_result[0]['geometry']['location']['lng'] #  Get the longitude
    
    print(address, 'is at', (lat, lng))