好记性不如铅笔头

python && jython, 编程

python学习笔记:使用百度API对IP进行解析

最近想重新拾起来python,就找了写小功能练练手,代码很简单,直接贴出来了,思路也很简单,直接利用百度API查询

import urllib.request
import json
import sys
import ipaddress

if __name__ == '__main__':
    
    arglen = len(sys.argv);
    if(arglen != 2):
        print("请输入IP地址");
        sys.exit();
    ipaddr = sys.argv[1];
    
    try:
        ipaddress.ip_address(ipaddr);
    except :
        print("IP地址不合法");
        sys.exit();
        
    httpURL = "http://api.map.baidu.com/location/ip?ak=xxxx&ip=%s&coor=bd09ll" %ipaddr;
    resultGet = urllib.request.urlopen(httpURL);   
    resultGet = str(resultGet.read(), encoding = "utf-8");   
    resultJson = json.loads(resultGet);
    if(resultJson['status'] != 0):
        print("查询失败");
        sys.exit();
    else:
        realAddr = resultJson['content']['address_detail']['province'] + \
                            resultJson['content']['address_detail']['city'] + \
                            resultJson['content']['address_detail']['district'] + \
                            resultJson['content']['address_detail']['street'] +\
                            resultJson['content']['address_detail']['street_number'] ;
        finalOut = "IP[%s]对应的地址为[%s],对应的经纬度[%s]"%(ipaddr,realAddr, resultJson['content']['point'] );
        print(finalOut);
        sys.exit();    

 

Leave a Reply

1 × 2 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据