本来想调用阿里的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)


wKiom1SHvnSy5mXdAACUq8a9nqg911.jpg

但是多次查询发现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)

wKiom1SHv5Ch3WojAAB9iRfaqo0333.jpg

测试也不错,公司要使用还是选择购买付费的库查询接口吧。