如何在 Python 中快速从 IP 地址列表中查找纬度/经度?

问题描述

我目前有一列 IP 地址,我想将这些地址与对应纬度/经度的列连接起来。

我目前正在使用以下方法,但速度非常慢:

def getting_ip(row,latlong):
    url = r'https://freegeoip.app/json/'+row
    headers = {
        'accept': "application/json",'content-type': "application/json"
        }
    response = requests.request("GET",url,headers=headers)
    respond = json.loads(response.text)
    if respond[latlong]:
      return respond[latlong]
    else:
      return None

df['Latitude'] = [getting_ip(i,'latitude') if i else None for i in df['IP']]
df['Longitude'] = [getting_ip(i,'longitude') if i else None for i in df['IP']]

在定义中使用 .apply 也不会为我节省太多时间,我大部分时间都花在取回请求上。有没有一种免费、简单的方法可以从 ip 地址获取纬度/经度(在几次请求后不会过期?)。

解决方法

为此,如果您更喜欢 python,那么我会找到这些包:

ip2geotools

ip2geotools 可以从 IP 地址中提取纬度和经度。

ip2geotools 是一个简单的工具,用于从各种地理定位数据库中获取给定 IP 地址的地理定位信息。这个包为多个地理定位数据库提供了一个 API。

示例如下:

>>> response = DbIpCity.get('147.229.2.90',api_key='free')
>>> response.ip_address
'147.229.2.90'
>>> response.city
'Brno (Brno střed)'
>>> response.region
'South Moravian'
>>> response.country
'CZ'
>>> response.latitude
49.1926824
>>> response.longitude
16.6182105
>>> response.to_json()
'{"ip_address": "147.229.2.90","city": "Brno (Brno střed)","region": "South Moravian","country": "CZ","latitude": 49.1926824,"longitude": 16.6182105}'
>>> response.to_xml()
'<?xml version="1.0" encoding="UTF-8" ?><ip_location><ip_address>147.229.2.90</ip_address><city>Brno (Brno střed)</city><region>South Moravian</region><country>CZ</country><latitude>49.1926824</latitude><longitude>16.6182105</longitude></ip_location>'
>>> response.to_csv(',')
'147.229.2.90,Brno (Brno střed),South Moravian,CZ,49.1926824,16.6182105'

Geoip2

另一个可用的包 geoip2 与此包类似,但具有异步请求处理支持和单独的数据库搜索选项。

如果需要,您可以查看他们的网站以获取同步和异步网络服务示例。

IP2location

由于此 API 主要是付费的,我尝试找到一个免费版本,我发现这个名为 Ip2location Python 的库可以在一个月内免费提供 30000 次查找。

,

您可以使用 IP2Location Python 库获取 IP 地址的纬度和经度。例如,

import os
import IP2Location

database = IP2Location.IP2Location(os.path.join("data","IP2LOCATION-LITE-DB5.BIN"))

rec = database.get_all("19.5.10.1")

print(rec.country_short)
print(rec.country_long)
print(rec.region)
print(rec.city)
print(rec.latitude)
print(rec.longitude)

上面的示例代码使用了 IP2Location LITE DB5 database。您可以在此处注册并免费获取数据库:https://lite.ip2location.com/sign-up