有没有办法使用Python获取计算机的物理位置,最好是没有API,或者使用免费的API?我已经搜索了一下,我发现的唯一免费API是非常非常不准确的。我只需要一点准确,因为这是为了获得当地的天气。
你可以从像http://www.geoiptool.com/这样的网页上删除它。
你可以尝试使用MaxMind's GeoIP Python API和他们的免费GeoLite City database。准确性可能会有所不同,更多details here。
另外,请查看this question以了解其他选择。
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']
将HTTP GET请求发送到:freegeoip.net/{format}/ {ip_or_hostname}以接收Python可以解析的JSON输出。
我得到以下JSON密钥,这应该足以满足您的需求:
我重新发现了另一个天气API,我不太喜欢(Weather Underground),但可以选择确定位置。如果我不能像geoiptool刮刀那样工作,可能会使用它。
如果你知道设备的公共IP,那么你可以使用freegeip。下面是获取位置和时区的Python 3.4.2代码。
>>> 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)])