宽屏模式

python 利用 geoip 批量查询 IP 归属地

# !/usr/bin/env python

# -*- coding:utf-8 -*-

import pandas as pd
import os
import geoip2.database
# 设置工作目录
os.chdir('G:/python/0-ip')

# 数据读取
df = pd.read_excel('1.xlsx', sheet_name = 0)
# print(df)
df_length = len(df)

# 读取'IP'列数据放入列表
ip_data = df.IP.tolist()
# print(ip)

city_data = []
isp_data = []
j = 1
reader = geoip2.database.Reader('G:/python/0-ip/GeoLite2-City.mmdb')
for i in ip_data:
    if(j==20):
        exit()
    try:
        data = reader.city(i)
    except geoip2.errors.AddressNotFoundError:
        city = '无'
        city_data.append(city)
        continue
    try:
        city = data.city.names['zh-CN']
    except KeyError:
        city = data.city.name
    print(data.city)

    country = data.country.name
    # 提取需要获取的信息并导入成为列表
    j = j+ 1
    city_data.append(city)
# 将数据整合为Dataframe类型
ipinfo = {"IP": ip_data, "城市": city_data}

result = pd.DataFrame(ipinfo)
# Dataframe输出为excel
result.to_excel('2.xlsx')

Larwas
请先登录后发表评论
  • latest comments
  • 总共0条评论