我有大约 300 个 IP 地址的列表,我想将其绘制在世界地图上。你能大致解释一下我如何使用 Python 做到这一点吗?
编辑:我也对问题的可视化部分感兴趣
您可以使用 hostip.info API。例如:
http://api.hostip.info/get_html.php?ip=64.233.160.0
所以使用
urllib2
的 Python 代码将是:
import urllib2
f = urllib2.urlopen("http://api.hostip.info/get_html.php?ip=64.233.160.0")
data = f.read()
f.close()
然后从返回的结果中检索数据。
如果您需要经度和纬度,请使用
position=true
标志:
http://api.hostip.info/get_html.php?ip=64.233.160.0&position=true
这是我在 Python 3.x 中的解决方案,在给定包含 IP 地址的数据帧的情况下返回 地理位置信息;在矢量化 pd.series/dataframe 上高效并行应用函数是可行的方法。
为了在地图上绘制记录,对纬度和经度信息进行子集化,然后使用合适的映射 API(例如 Google Maps Api 或 tableau)有助于实现数据可视化。
将对比两个流行库的性能以返回位置。
TLDR:使用geolite2方法。
1.
geolite2
来自 geolite2
库的包
输入
# !pip install maxminddb-geolite2
import time
from geolite2 import geolite2
geo = geolite2.reader()
df_1 = train_data.loc[:50,['IP_Address']]
def IP_info_1(ip):
try:
try:
x = geo.get(ip)
except ValueError: #Faulty IP value
return np.nan
try:
return x['country']['names']['en'] if x is not None else np.nan
except KeyError: #Faulty Key value
return np.nan
s_time = time.time()
# map IP --> country
#apply(fn) applies fn. on all pd.series elements
df_1['country'] = df_1.loc[:,'IP_Address'].apply(IP_info_1)
print(df_1.head(), '\n')
print('Time:',str(time.time()-s_time)+'s \n')
print(type(geo.get('48.151.136.76')))
输出
IP_Address country
0 48.151.136.76 United States
1 94.9.145.169 United Kingdom
2 58.94.157.121 Japan
3 193.187.41.186 Austria
4 125.96.20.172 China
Time: 0.09906983375549316s
<class 'dict'>
2.
DbIpCity
来自 ip2geotools
库的包
输入
# !pip install ip2geotools
import time
s_time = time.time()
from ip2geotools.databases.noncommercial import DbIpCity
df_2 = train_data.loc[:50,['IP_Address']]
def IP_info_2(ip):
try:
return DbIpCity.get(ip, api_key = 'free').country
except:
return np.nan
df_2['country'] = df_2.loc[:, 'IP_Address'].apply(IP_info_2)
print(df_2.head())
print('Time:',str(time.time()-s_time)+'s')
print(type(DbIpCity.get('48.151.136.76',api_key = 'free')))
输出
IP_Address country
0 48.151.136.76 US
1 94.9.145.169 GB
2 58.94.157.121 JP
3 193.187.41.186 AT
4 125.96.20.172 CN
Time: 80.53318452835083s
<class 'ip2geotools.models.IpLocation'>
巨大的时间差异可能是由于输出的数据结构造成的,i.e.从dictionaries直接子集似乎比从专门的ip2geotools.models.IpLocation对象进行索引更有效。
此外,第一种方法的输出是包含地理位置数据的字典,分别子集以获得所需的信息:
x = geolite2.reader().get('48.151.136.76')
print(x)
>>>
{'city': {'geoname_id': 5101798, 'names': {'de': 'Newark', 'en': 'Newark', 'es': 'Newark', 'fr': 'Newark', 'ja': 'ニューアーク', 'pt-BR': 'Newark', 'ru': 'Ньюарк'}},
'continent': {'code': 'NA', 'geoname_id': 6255149, 'names': {'de': 'Nordamerika', 'en': 'North America', 'es': 'Norteamérica', 'fr': 'Amérique du Nord', 'ja': '北アメリカ', 'pt-BR': 'América do Norte', 'ru': 'Северная Америка', 'zh-CN': '北美洲'}},
'country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': 'アメリカ合衆国', 'pt-BR': 'Estados Unidos', 'ru': 'США', 'zh-CN': '美国'}},
'location': {'accuracy_radius': 1000, 'latitude': 40.7355, 'longitude': -74.1741, 'metro_code': 501, 'time_zone': 'America/New_York'},
'postal': {'code': '07102'},
'registered_country': {'geoname_id': 6252001, 'iso_code': 'US', 'names': {'de': 'USA', 'en': 'United States', 'es': 'Estados Unidos', 'fr': 'États-Unis', 'ja': 'アメリカ合衆国', 'pt-BR': 'Estados Unidos', 'ru': 'США', 'zh-CN': '美国'}},
'subdivisions': [{'geoname_id': 5101760, 'iso_code': 'NJ', 'names': {'en': 'New Jersey', 'es': 'Nueva Jersey', 'fr': 'New Jersey', 'ja': 'ニュージャージー州', 'pt-BR': 'Nova Jérsia', 'ru': 'Нью-Джерси', 'zh-CN': '新泽西州'}}]}
您可以使用GeoIP,它有免费和付费版本。还有一个方便的 Python API。
使用
ipapi
API。它比ip2geotools
(不需要安装Visual C++ 14.0)或hostip.info API
(不是很准确)或上面提到的其他可能不会超出国家/地区要好得多。
import requests
arr1=["ipaddress1","ipaddress2",...,"ipaddress300"]
def get_location(ip):
ip_address = ip
response = requests.get(f'https://ipapi.co/{ip_address}/json/').json()
location_data = {
"ip": ip_address,
"city": response.get("city"),
"region": response.get("region"),
"country": response.get("country_name")
}
return location_data
for ip in arr1:
print(get_location(ip))
对于可视化,您有很多选项,例如 底图、folium、geopandas 和plotly。
感谢来自 https://www.freecodecamp.org/news/how-to-get-location-information-of-ip-address-using-python/