What python libraries can tell me approximate location and time zone given an IP address?

后端 未结 13 699
借酒劲吻你
借酒劲吻你 2020-11-28 03:31

Looking to implement better geo-location with Python.

相关标签:
13条回答
  • 2020-11-28 04:32

    I posted this in another question that had been buried, but linked here:

    #!/usr/bin/env python 
    from urllib2 import urlopen
    from contextlib import closing
    import json
    
    # Automatically geolocate the connecting IP
    url = 'http://freegeoip.net/json/'
    try:
        with closing(urlopen(url)) as response:
            location = json.loads(response.read())
            print(location)
            location_city = location['city']
            location_state = location['region_name']
            location_country = location['country_name']
            location_zip = location['zipcode']
    except:
        print("Location could not be determined automatically")
    

    Send HTTP GET requests to: freegeoip.net/{format}/{ip_or_hostname} to receive a JSON output that Python can parse.

    I get the following JSON keys, which should be sufficient for what you are needing:

    • ip
    • country_code
    • country_name
    • region_code
    • region_name
    • city
    • zipcode
    • latitude
    • longitude
    • metro_code
    • area_code
    0 讨论(0)
提交回复
热议问题