0
点赞
收藏
分享

微信扫一扫

IP地址归属地批量查询python代码

import pandas as pd
import requests

def get_ip_info(ip):
    try:
        url = f"https://ip.zxinc.org/api.php?type=json&ip={ip}"
        response = requests.get(url)
        data = response.json()
        if data['code'] == 0:
            return data['data']['country'], data['data']['local']
        else:
            return "Error", "Error"
    except requests.RequestException:
        return "Error", "Error"
    
def read_ips_from_file(file_path, column_name):
    if file_path.endswith('.csv'):
        df = pd.read_csv(file_path)
    else:
        df = pd.read_excel(file_path)
    return df[column_name]

def write_results_to_file(file_path, data):
    if file_path.endswith('.csv'):
        data.to_csv(file_path, index=False)
    else:
        data.to_excel(file_path, index=False)

file_path = r'your file path'  # 修改为你的包含IP地址的文件路径,支持excel与csv
ips = read_ips_from_file(file_path, column_name='ip')  # 修改为你的列名

results = []
for ip in ips:
    country, local = get_ip_info(ip)
    results.append([ip, country, local])

output_df = pd.DataFrame(results, columns=['IP', 'Country', 'Local'])
output_file_path = r'your output file path'  # 修改为你想要的输出文件名
write_results_to_file(output_file_path, output_df)


举报

相关推荐

0 条评论