python geoip2库,根据ip获取地理位置
1、要下载一个ip库,用来匹配解析与ip相关的参数。
在MaxMind官网进行geoip2账户注册,可下载安装geoip2,支持免费和付费的不同ip库,可下载免费的mmdb格式的IP库文件(GeoLite2-City.mmdb)
2、安装geoip2
依赖库
pip install geoip2
3、方法例子
(将ip库文件 和.py脚本文件 存放在相同的文件夹下 ../main/)
# main/test.py
from geoip2 import database
def main(ip):
with database.Reader('GeoLite2-City.mmdb') as reader:
response = reader.city(ip)
print(f'全量数据:\t\t{response}')
print(f'国家编码:\t\t{response.country.iso_code}')
print(f'国家英文名称:\t{response.country.name}')
print(f'国家中文名称:\t{response.country.names.get("zh-CN")}')
print(f'州/省编码:\t\t{response.subdivisions.most_specific.iso_code}')
print(f'州/省英文名称:\t{response.subdivisions.most_specific.name}')
print(f'州/省中文名称:\t{response.subdivisions.most_specific.names.get("zh-CN")}')
print(f'城市英文名称:\t{response.city.name}')
print(f'城市中文名称:\t{response.city.names.get("zh-CN")}')
print(f'城市编码:\t\t{response.postal.code}')
print(f'城市经度:\t\t{response.location.longitude}')
print(f'城市纬度:\t\t{response.location.latitude}')
print('-' * 50)
if __name__ == '__main__':
main('123.73.135.253')
参考地址:MaxMind GeoIP2 API