首页 » Program » Python » 正文

利用百度api高精度定位IP

一段时间前利用百度api写了个高精度定位ip的python脚本,接口说明:http://lbsyun.baidu.com/index.php?title=webapi/high-acc-ip

不过服务现在暂不可用(不知道为什么,可能有bug),我写这个脚本的时候还是能用的。

#coding:utf-8
#Author:LSA
#Date:201610301543
#Description:To find high accuracy IP location,use baidu map api

import sys,urllib2,json

def get_highacciploc(ip):
    url='https://api.map.baidu.com/highacciploc/v1?qcip='+ip+'&qterm=pc&ak=youkey&coord=bd09ll&extensions=3'
    poiss=''
    request = urllib2.Request(url)
    page=urllib2.urlopen(request,timeout=10)
    data_json=page.read()
    data_dic=json.loads(data_json)
    
    if(data_dic.has_key("result")):
            result=data_dic["result"]
            
    if(result["error"]==161):
        print "success position!"
        if(data_dic.has_key("content")):
            content=data_dic["content"]
            address_component=content["address_component"]
            formatted_address=content["formatted_address"]
            credibility=content["confidence"]
            print "the ip location is :        confidence("+str(credibility)+")"
            print address_component["country"]
            print formatted_address
            if(content.has_key("pois")):
                print "the ip's pios : "
                pois=content["pois"]
                for index in range(len(pois)):
                    pois_name=pois[index]["name"]
                    pois_address=pois[index]["address"]
                    print pois_name,pois_address
        
    else:   
        print "ip position error!("+str(result["error"])+")"

if __name__=='__main__':
    ip=raw_input("Please input the ip: ")
    get_highacciploc(ip)

结果貌似不怎么准确,用个错误的ip地址还把pois信息爆出来了…….不过倒是挺好玩的。

Comment