根据IP查询城市ID和名字
python
import json
import time
import geoip2.database
import requests
from loguru import logger
#创建GeoIP对象,并指定数据库路径
reader = geoip2.database.Reader(r'D:\thb\code\python-trial\pythonProject\data\GeoLite2-City.mmdb')
#web addr: https://ip.taobao.com/ipSearch
#淘宝 IP 库提供的 Rest 风格接口:10qps
def query_china_ip_location(ipaddress: str):
req_params={
"ip": ipaddress,
"accessKey":"alibaba-inc"
}
cityid=None
cityname=None
rsp=requests.post(url="http://ip.taobao.com/outGetIpInfo",data=req_params)
'''
{
"data": {
"area": "",
"country": "中国",
"isp_id": "100017",
"queryIp": "118.251.69.6",
"city": "株洲",
"ip": "118.251.69.6",
"isp": "电信",
"county": "",
"region_id": "430000",
"area_id": "",
"county_id": null,
"region": "湖南",
"country_id": "CN",
"city_id": "430200"
},
"msg": "query success",
"code": 0
}
'''
if rsp.status_code == 200:
logger.info("result:{}",rsp.text)
data_dict=json.loads(rsp.text)
if data_dict.get("data") is not None:
cityid = data_dict.get("data").get("city_id")
cityname = data_dict.get("data").get("city")
return cityid,cityname
#基于maxmind的IP查询,适合于国外IP
def query_ip_location(ip):
try:
# 查询IP归宿地
response = reader.city(ip)
# 提取国家名称
country = response.country.name
# 提取城市信息,如果存在的话
city = response.city.name
if city:
return f"{country} | {city}"
else:
return country
except geoip2.errors.AddressNotFoundError:
return "IP地址未找到"
if __name__ == "__main__":
#测试查询
#ip_location = query_ip_location('128.101.101.101')
#print(ip_location)
ip_addrs=["118.124.102.247","183.222.178.180","117.183.162.183","118.251.69.6"]
for ip_address in ip_addrs:
time.sleep(1)
cityid,cityname=query_china_ip_location(ip_address)
logger.info("cityid:{},cityname:{}",cityid,cityname)