首页 > 编程知识 正文

Python批量查询IP位置

时间:2023-11-19 22:40:41 阅读:301319 作者:VZYM

本文将详细介绍如何使用Python编写代码来批量查询IP地址的位置。

一、IP查询服务

在开始编写代码之前,我们需要了解一些IP查询服务。目前有很多提供免费查询IP位置的API服务,例如,通过“ip-api.com”可以查询某个IP的位置信息。

以下是使用该API查询IP位置的Python代码示例:

import requests

def get_ip_location(ip):
    response = requests.get(f"http://ip-api.com/json/{ip}")
    data = response.json()
    country = data.get("country")
    city = data.get("city")
    return f"IP: {ip}, Location: {country}, {city}"

# 批量查询IP位置
ip_list = ["IP1", "IP2", "IP3"]
for ip in ip_list:
    location = get_ip_location(ip)
    print(location)

二、IP查询结果

查询IP位置后,返回的结果通常包括IP地址、国家和城市等信息。你可以根据自己的需要对查询结果进行处理。

以下是对查询结果进行处理的示例代码:

# 处理查询结果
def process_location(location):
    ip, country, city = location.split(",")
    ip = ip.split(":")[1].strip()
    country = country.split(":")[1].strip()
    city = city.split(":")[1].strip()
    return f"IP: {ip}, Location: {country}, {city}"

# 批量查询IP位置
ip_list = ["IP1", "IP2", "IP3"]
for ip in ip_list:
    location = get_ip_location(ip)
    processed_location = process_location(location)
    print(processed_location)

三、批量查询

如果需要批量查询一组IP的位置,可以将IP地址存储在一个文件中,然后逐行读取文件,并进行查询。

以下是批量查询IP位置的示例代码:

# 读取IP列表
def read_ip_list(filename):
    with open(filename, "r") as file:
        ip_list = [line.strip() for line in file]
    return ip_list

# 批量查询IP位置
filename = "ip_list.txt"
ip_list = read_ip_list(filename)
for ip in ip_list:
    location = get_ip_location(ip)
    processed_location = process_location(location)
    print(processed_location)

四、IP查询结果保存

如果需要将查询结果保存到文件中,可以将每个IP的位置信息逐行写入文件。

以下是将查询结果保存到文件的示例代码:

# 保存查询结果
def save_location(filename, locations):
    with open(filename, "w") as file:
        for location in locations:
            file.write(location + "n")

# 批量查询IP位置
filename = "ip_list.txt"
ip_list = read_ip_list(filename)
all_locations = []
for ip in ip_list:
    location = get_ip_location(ip)
    processed_location = process_location(location)
    all_locations.append(processed_location)

# 保存查询结果
save_location("location.txt", all_locations)

总结

通过使用Python编写代码,我们可以方便地批量查询IP地址的位置信息。通过调用IP查询服务API,我们可以获取IP的国家和城市等详细信息,并可以根据需要进行进一步处理和保存。

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。