查询本机IP及精确地理位置

来源:互联网 发布:网络节点怎么设置 编辑:程序博客网 时间:2024/04/30 11:17

使用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(r'\d+\.\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[u'data'][u'country'].encode(bianma)        data += " "+kk_dict[u'data'][u'region'].encode(bianma)        data += " "+kk_dict[u'data'][u'city'].encode(bianma)        data += " "+kk_dict[u'data'][u'county'].encode(bianma)        data += " "+kk_dict[u'data'][u'isp'].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 '\n\n'    #请按任意键继续    if os.name == 'nt':        os.system('pause')    else:        raw_input(u"请按任意键继续。。。".encode(bianma))


0 0
原创粉丝点击