Get physical position of device with Python?

前端 未结 5 2081
深忆病人
深忆病人 2021-01-20 11:51

Is there a way to get the computer\'s physical position using Python, preferably without an API, or with a free API? I\'ve searched around a bit, and the only free API I\'ve

相关标签:
5条回答
  • 2021-01-20 12:04
    import urllib2
    import json
    
    # Automatically geolocate the connecting IP
    f = urllib2.urlopen('http://freegeoip.net/json/')
    json_string = f.read()
    f.close()
    location = json.loads(json_string)
    print(location)
    location_city = location['city']
    location_state = location['region_name']
    location_country = location['country_name']
    location_zip = location['zipcode']
    

    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)
  • 2021-01-20 12:04

    I rediscovered another weather API which I don't like quite as much (Weather Underground), but can optionally determine the location. Might use this if I can't something like a geoiptool scraper to work.

    0 讨论(0)
  • 2021-01-20 12:07

    You can try using MaxMind's GeoIP Python API with their free GeoLite City database. Accuracy may vary, more details here.

    Also take a look at this question for other alternatives.

    0 讨论(0)
  • 2021-01-20 12:09

    If you know the public IP of the device then you can do so by using freegeip. Below is the Python 3.4.2 code for getting location and time zone.

    >>> import requests
    >>> ip = '141.70.111.66'
    >>> url = 'http://freegeoip.net/json/'+ip
    >>> r = requests.get(url)
    >>> js = r.json()
    >>> js['country_code']
    'DE'
    >>> js['country_name']
    'Germany'
    >>> js['time_zone']
    'Europe/Berlin'
    >>> js['city']
    'Stuttgart'
    >>> js.items()
    dict_items([('latitude', 48.7667), ('ip', '141.70.111.66'), ('region_code', 'BW'), ('country_code', 'DE'), ('city', 'Stuttgart'), ('zip_code', '70173'), ('country_name', 'Germany'), ('longitude', 9.1833), ('region_name', 'Baden-Württemberg Region'), ('time_zone', 'Europe/Berlin'), ('metro_code', 0)])
    
    0 讨论(0)
  • 2021-01-20 12:19

    You can scrape it from a webpage like http://www.geoiptool.com/ for example.

    0 讨论(0)
提交回复
热议问题