如何用IP地址在Python中查找位置?
我正在开发一个项目,需要在我的数据库中存储用户的位置。我得到了用户的公共IP地址,但我无法获取用户的位置。我尝试了几种方法(来自StackOverflow),但没有找到任何线索。比如下面这个:
url = urllib.urlopen("http://api.hostip.info/get_html.php?ip=%s&position=true" % ip)
data = re.compile('^[^\(]+\(|\)$').sub('', url.read())
print data
但是我得到的结果是:
Unknown Country?) (XX)
City: (Unknown City?)
还有另一种方法:
import urllib
response = urllib.urlopen("http://api.hostip.info/get_html.php?ip={}&position=true".format(ip)).read()
print(response)
但是结果是:
Country: (Unknown Country?) (XX)
City: (Unknown City?)
Latitude:
Longitude:
IP: 115.xxx.xxx.xx
任何帮助都会很感激!
14 个回答
11
你可以使用https://geolocation-db.com提供的服务,它支持IPv4和IPv6。你可以得到一个JSON对象或者一个JSONP回调函数作为返回结果。
Python 2的示例:
import urllib
import json
url = "https://geolocation-db.com/json"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data
Python 3的示例:
import urllib.request
import json
with urllib.request.urlopen("https://geolocation-db.com/json") as url:
data = json.loads(url.read().decode())
print(data)
这是一个Python 3的jsonp示例:
import urllib.request
import json
with urllib.request.urlopen("https://geolocation-db.com/jsonp/8.8.8.8") as url:
data = url.read().decode()
data = data.split("(")[1].strip(")")
print(data)
22
感谢大家提供的各种解决方案和替代方法!
不过,我并没有办法使用上面提到的所有方法。
以下是我找到的有效方法:
import requests
response = requests.get("https://geolocation-db.com/json/39.110.142.79&position=true").json()
这个方法看起来简单易用。(我需要处理一个字典格式的响应...)
将来,“geolocation-db.com”可能会无法使用,所以可能需要寻找其他来源!
23
适用于python-3.x
def ipInfo(addr=''):
from urllib.request import urlopen
from json import load
if addr == '':
url = 'https://ipinfo.io/json'
else:
url = 'https://ipinfo.io/' + addr + '/json'
res = urlopen(url)
#response from url(if res==None then check connection)
data = load(res)
#will load the json response into data
for attr in data.keys():
#will print the data line by line
print(attr,' '*13+'\t->\t',data[attr])
46
获取IP地址和详细位置的最简单方法之一就是使用 http://ipinfo.io
import re
import json
from urllib2 import urlopen
url = 'http://ipinfo.io/json'
response = urlopen(url)
data = json.load(response)
IP=data['ip']
org=data['org']
city = data['city']
country=data['country']
region=data['region']
print 'Your IP detail\n '
print 'IP : {4} \nRegion : {1} \nCountry : {2} \nCity : {3} \nOrg : {0}'.format(org,region,country,city,IP)