有没有一种使用Python获取计算机物理位置的方法,最好不使用API或使用免费API?我已经搜索了一下,但是我发现唯一的免费API非常不准确。我只需要它相对准确一些,因为我要用它来获取本地天气。
有没有一种使用Python获取计算机物理位置的方法,最好不使用API或使用免费API?我已经搜索了一下,但是我发现唯一的免费API非常不准确。我只需要它相对准确一些,因为我要用它来获取本地天气。
有没有一种方法可以使用Python获取计算机的物理位置,最好不需要API或免费API
是的。使用IPinfo.io,您可以免费进行50000次请求/月。如果您想获取天气数据,可以通过进行IP地理位置查找来使用提供的region
或city
值。您可以通过使用请求库与API通信或使用IPinfo Python库来使用IPinfo API
requests
与API通信import requests
# here I have generated this IP address randomly
ip_address = "19.145.189.86"
# get your token from your IPinfo account dashboard
token = ""
# using f-string here. Use any method to create the URL
url = f"https://ipinfo.io/{ip_address}?token={token}"
# json response after the IP lookup
response = requests.get(url).json()
{
"ip": "19.145.189.86",
"city": "Dearborn",
"region": "Michigan",
"country": "US",
"loc": "42.2399,-83.1508",
"postal": "48121",
"timezone": "America/Detroit"
}
city
或region
值。因此,从response
字典中查找city
和region
的值。>>> response['city']
"Dearborn"
>>> response['region']
"Dearborn"
IPinfo Python库可以使这个过程更加容易。使用pip
进行安装。IPinfo Python文档
# install with `pip install ipinfo`
import ipinfo
# initialize handler with access token
access_token = "insert_your_token_here"
handler = ipinfo.getHandler(access_token)
ip_address = '19.145.189.86'
details = handler.getDetails(ip_address)
现在你可以从details
变量中找到你需要的个人信息。
>>> details.city
'Dearborn'
>>> details.region
'Michigan'
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']
GeoIP
数据库更糟糕,你可以离线下载并且不必担心这些服务宕机或从服务器下载数据所需的时间。 - jamylak如果您知道设备的公共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)])
进入 https://python-visualization.github.io/folium/plugins.html 发现,这非常简单,我的朋友 folium.plugins.LocateControl
我重新发现了另一个天气API,虽然我不太喜欢它(Weather Underground),但可以选择确定位置。如果我无法让类似于geoiptool的爬虫工作,可能会使用它。