Python IP Address to Location: GeoIP & API Methods
There are several ways to get user location information from an IP address in Python. Here are two popular methods:
- Using the GeoIP library:
pip install GeoIP
import GeoIP
gi = GeoIP.open('GeoIP.dat', GeoIP.GEOIP_STANDARD)
ip_address = '123.123.123.123'
location = gi.record_by_addr(ip_address)
print(location['country_name'])
print(location['city'])
This code uses the GeoIP library to open a database file (in this case, 'GeoIP.dat') and look up the location information for an IP address (in this case, '123.123.123.123'). The location information is returned as a dictionary, which you can use to extract specific pieces of data (such as the country name and city).
- Using an API:
import requests
ip_address = '123.123.123.123'
url = 'https://ipinfo.io/' + ip_address + '/json'
response = requests.get(url)
data = response.json()
print(data['country'])
print(data['city'])
This code uses the ipinfo.io API to look up the location information for an IP address (in this case, '123.123.123.123'). The API returns the location data in JSON format, which you can parse using the json
module. Again, you can extract specific pieces of data from the JSON object (such as the country and city). Note that you will need to sign up for a free API key from ipinfo.io to use this code.

原文地址: http://www.cveoy.top/t/topic/myA7 著作权归作者所有。请勿转载和采集!