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

2024-10-04 09:19:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前有一列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地址获取纬度/经度(几次请求后不会过期?)


Tags: 方法ipnonejsonurldfifelse
2条回答

您可以使用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

为此,如果您更喜欢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,它与此包类似,但具有异步请求处理支持和单独的数据库搜索选项

如果需要的话,您可以查看他们的网站上的同步和异步web服务示例

IP2定位

由于这个API大部分是付费的,我试图找到一个免费版本,我发现这个名为Ip2location Python的库,它在一个月内为您提供30000次免费查找

相关问题 更多 >