python3 调用淘宝接口查询IP所在地
学习python中,突然想做一道练习题。编写python查询ip来源信息。网上也参考了一些,
主要参考了:https://blog.51cto.com/10321203/2387650?source=dra
运行环境:
python3
国内查询ip地址:http://ip.taobao.com//service/getIpInfo.php?ip=
格式:
{"code":0,"data":{"ip":"171.213.8.140","country":"中国","area":"","region":"四川","city":"成都","county":"XX","isp":"电信","country_id":"CN","area_id":"","region_id":"510000","city_id":"510100","county_id":"xx","isp_id":"100017"}}
国外查询ip地址:http://ip-api.com/json/
格式:
{"status":"success","country":"China","countryCode":"CN","region":"SC","regionName":"Sichuan","city":"Chengdu","zip":"","lat":30.6667,"lon":104.0667,"timezone":"Asia/Shanghai","isp":"Chinanet","org":"Chinanet SC","as":"AS4134 No.31,Jin-rong Street","query":"171.213.8.140"}
直接上代码:
#!/usr/bin/env python3 # -*- coding:utf-8 -*- import requests import sys IP = input("请输入:"); def git_ip_info(ip): url ="http://ip.taobao.com//service/getIpInfo.php?ip=" + IP url2 = "http://ip-api.com/json/" + IP try: res = requests.get(url) res2 = requests.get(url2) except : print("连接出现异常啦!请在网页端确定URL可用") else: if res.json()['code'] ==0 : i = res.json()['data'] country = i['country'] area = i['area'] region = i['region'] city = i['city'] isp = i['isp'] print("******************************") print("您查询的ip地址 %s 来源是:" %res) print("国家:%s" %country) print("区域:%s" %area) print("省份:%s" %region) print("城市: %s" %city) print("运营商: %s" %isp) print("数据来源是淘宝IP地址库") print("******************************") strpp={} strpp=res2.json() print("*******************************") print("您查询的IP地址 %s 来源是:"%(strpp.get('query'))) print("国家:%s"%(strpp.get('country'))) print("城市:%s"%(strpp.get('city'))) print("经纬度坐标:%s,%s"%(strpp.get('lat'),strpp.get('lon'))) print("运营商编号:%s"%(strpp.get('as'))) print("ISP服务商:%s"%(strpp.get('isp'))) print("********************************") else: print("查询过于频繁会被主机拒绝连接,请重新运行!") ip = {'ip':IP} git_ip_info(ip)
运行截图: