python3制作简单的ip提取
字数 908 2025-08-18 11:37:02
Python3 IP归属地查询与筛选教程
一、环境准备
1. Python版本
- 使用Python3.x版本
- 推荐使用Linux系统,Windows也可运行
2. 必要模块安装
需要安装requests模块用于HTTP请求:
pip install requests
安装时会自动安装依赖:
- chardet (>=3.0.2, <3.1.0)
- idna (>=2.5, <2.7)
- urllib3 (>=1.21.1, <1.23)
- certifi (>=2017.4.17)
二、IP查询接口说明
使用淘宝IP地址库接口:
- 接口地址:
http://ip.taobao.com/service/getIpInfo.php?ip=[ip地址] - 请求方式:GET
- 返回格式:JSON
响应数据结构示例
{
"code": 0,
"data": {
"ip": "210.75.225.254",
"country": "中国",
"area": "华北",
"region": "北京市",
"city": "北京市",
"county": "",
"isp": "电信",
"country_id": "86",
"area_id": "100000",
"region_id": "110000",
"city_id": "110000",
"county_id": "-1",
"isp_id": "100017"
}
}
code: 0表示成功,1表示失败region: 省份信息(如"山西省")
三、核心代码实现
1. 基础查询函数
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import requests
def checkip(ip):
try:
URL = 'http://ip.taobao.com/service/getIpInfo.php?ip=' + ip
r = requests.get(URL, timeout=3)
json_data = r.json()
region = json_data['data']['region']
return region
except:
return None
2. 文件读取与处理
with open('ips.txt') as f:
ips = f.read().split("\n") # 按行读取IP并分割成列表
for ip in ips:
region = checkip(ip)
if region == '山西省':
print(ip)
3. 结果写入文件
with open('result.txt', 'a') as fw:
fw.write('\n' + ip) # 追加模式写入符合条件的IP
四、完整代码示例
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import requests
def checkip(ip):
try:
URL = 'http://ip.taobao.com/service/getIpInfo.php?ip=' + ip
r = requests.get(URL, timeout=3)
json_data = r.json()
region = json_data['data']['region']
return region
except:
return None
with open('ips.txt') as f:
ips = f.read().split("\n")
with open('shanxi_ips.txt', 'w') as fw:
for ip in ips:
if ip.strip(): # 跳过空行
region = checkip(ip)
if region == '山西省':
fw.write(ip + '\n')
五、关键知识点
1. 异常处理
- 使用
try/except防止程序因异常中断 - 处理网络请求超时、JSON解析错误等情况
2. 文件操作模式
| 模式 | 描述 |
|---|---|
| r | 只读(默认) |
| w | 写入(覆盖) |
| a | 追加 |
| r+ | 读写 |
| w+ | 写读(覆盖) |
| a+ | 追加读写 |
| b | 二进制模式 |
3. 上下文管理器
使用with语句自动管理文件资源:
with open('file.txt') as f:
data = f.read()
# 文件会自动关闭
六、优化建议
- 添加进度显示:处理大量IP时可显示进度
- 多线程处理:加快批量查询速度
- 缓存机制:避免重复查询相同IP
- 参数化配置:将目标省份、输入输出文件名设为参数
- 日志记录:记录处理过程和错误信息
七、扩展应用
- 可修改为查询任意指定地区的IP
- 可统计各地区IP数量分布
- 可结合其他IP库接口提高准确性
- 可开发为可视化工具展示IP地理分布
通过本教程,您已掌握使用Python3通过第三方接口查询IP归属地并筛选特定地区IP的核心方法。可根据实际需求进一步扩展和完善功能。