Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
188 views
in Technique[技术] by (71.8m points)

How to find location with IP address in Python?

I am developing a project, that needs to store user location in my data base. I got the public IP address of that user. But I am unable to get the user location. I have tried several ways (from StackOverflow) but I didn't find any hint. Like the below

url = urllib.urlopen("http://api.hostip.info/get_html.php?ip=%s&position=true" % ip)
data = re.compile('^[^(]+(|)$').sub('', url.read())
print data

but I am getting the result as

Unknown Country?) (XX)
City: (Unknown City?)

another way:

import urllib

response = urllib.urlopen("http://api.hostip.info/get_html.php?ip={}&position=true".format(ip)).read()

print(response)

but the result is

Country: (Unknown Country?) (XX)
City: (Unknown City?)

Latitude: 
Longitude: 
IP: 115.xxx.xxx.xx

Any help would be appreciated!

question from:https://stackoverflow.com/questions/24678308/how-to-find-location-with-ip-address-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One of the simplest methods for getting the IP address as well as the location in detail is to use 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
 '
print 'IP : {4} 
Region : {1} 
Country : {2} 
City : {3} 
Org : {0}'.format(org,region,country,city,IP)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...