查询本机IP及精确地理位置
使用API查询IP对应的具体位置,注意点:
1.淘宝ip地址库http://ip.taobao.com/instructions.php,按照说明操作即可
第一行#linux系统中,指定python启动位置
2.利用os.name识别操作系统,针对不同的操作系统,设置不同的编码
3.养成好的编程习惯,在python中所有中文,写成格式:u"地理位置:".encode(bianma)+str(data)
#!/usr/bin/env python
#coding=utf-8
__author__="zq"
import urllib2,re,os,json
#识别操作系统,设置编码
if os.name == "nt":
bianma = GBK
else:
bianma = utf-8
def getIp():
ipinfo = ""
w_ip = ""
#使用某些网页服务,获取本地ip
try:
ipinfo = urllib2.urlopen("http://members.3322.org/dyndns/getip")
w_ip = ipinfo.read()
#print ipinfo
except:
try:
ipinfo = urllib2.urlopen("http://www.ip138.com/").read()
#正则表达式匹配网页中的ip
w_ip = re.search(rd+.d+.d+.d+,ipinfo).group(0)
print w_ip
except:
pass
#使用“淘宝ip地址库”API查询精确位置
try:
kk = urllib2.urlopen(http://ip.taobao.com/service/getIpInfo.php?ip=%s%str(w_ip)).read()
#将返回json格式字符串转化为字典
kk_dict = json.loads(kk)
#提取字典中的元素
data = kk_dict[udata][ucountry].encode(bianma)
data += " "+kk_dict[udata][uregion].encode(bianma)
data += " "+kk_dict[udata][ucity].encode(bianma)
data += " "+kk_dict[udata][ucounty].encode(bianma)
data += " "+kk_dict[udata][uisp].encode(bianma)
except Exception,e:
print u"获取外网的ip地址失败".encode(bianma)
print str(e)
print u"外网ip:".encode(bianma)+str(w_ip)
print u"地理位置:".encode(bianma)+str(data)
if __name__ == __main__:
#为显示方便,先清屏
if os.name == nt:
os.system(cls)
else:
os.system(clear)
print -*50
print u"本程序用于查询Ip地理位置".encode(bianma)
print -*50
getIp()
print
#请按任意键继续
if os.name == nt:
os.system(pause)
else:
raw_input(u"请按任意键继续。。。".encode(bianma))
