使方法一、用IP138数据库查询域名或IP地址对应的地理位置。
#-*- coding:gbk -*- import urllib2 import re try: while True: ipaddr = raw_input(\"Enter IP Or Domain Name:\") if ipaddr == \"\" or ipaddr == \'exit\': break else: url = \"http://www.ip138.com/ips138.asp?ip=%s&action=2\" % ipaddr u = urllib2.urlopen(url) s = u.read() #Get IP Address ip = re.findall(r\'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\',s) print \"\\n****** Below Result From IP138 Database *****\" print \"IP Address:\",ip[0] #Get IP Address Location result = re.findall(r\'(
方法二、本来想调用阿里的ip接口查询ip归属地。结果发现阿里的接口非常不给力,主要是不准确,不过是免费的且有地区和ISP的信息。以下是实现代码
# -*- coding: utf-8 -*- import requests def checkip(ip): URL = \'http://ip.taobao.com/service/getIpInfo.php\' try: r = requests.get(URL, params=ip, timeout=3) except requests.RequestException as e: print(e) else: json_data = r.json() if json_data[u\'code\'] == 0: print \'所在国家: \' + json_data[u\'data\'][u\'country\'].encode(\'utf-8\') print \'所在地区: \' + json_data[u\'data\'][u\'area\'].encode(\'utf-8\') print \'所在省份: \' + json_data[u\'data\'][u\'region\'].encode(\'utf-8\') print \'所在城市: \' + json_data[u\'data\'][u\'city\'].encode(\'utf-8\') print \'所属运营商:\' + json_data[u\'data\'][u\'isp\'].encode(\'utf-8\') else: print \'查询失败,请稍后再试!\' ip={\'ip\': \'202.102.193.68\'} checkip(ip)
但是多次查询发现ip归属地不准确,于是使用17mon的ip查询接口。但是17mon分付费和免费的库接口,我用的免费的测试,接口返回的字段有限,只有国家、省份、城市。代码如下
# -*- coding: utf-8 -*- import requests def lookup(ip): URL = \'http://freeipapi.17mon.cn/\' + ip try: r = requests.get(URL, timeout=3) except requests.RequestException as e: print(e) json_data = r.json() print \'所在国家:\' + json_data[0].encode(\'utf-8\') print \'所在省份:\' + json_data[1].encode(\'utf-8\') print \'所在城市:\' + json_data[2].encode(\'utf-8\') return(ip) ip=\'202.104.15.102\' lookup(ip)
测试也不错,公司要使用还是选择购买付费的库查询接口吧。
本文部分出自 “老徐的私房菜” 博客,转载请与作者联系!
以上所述就是本文的全部内容了希望大家能够喜欢。
上一篇:python实现定时播放mp3
下一篇:python实现定时播放mp3