Python转换IP为具体地理位置小脚本


     近期工作中涉及到处理后台日志,要将大量IP数据转换成具体的地理位置,如“国家-省-市”。去网上找了一下,有很多可以拉过来用的方法,参考这篇文章,http://ju.outofmemory.cn/entry/77846,提供了比较完整的实现方式和具体代码。以此为基础,经过小小修改,任务得以顺利完成。

# !/usr/bin/python
# -*- coding: utf-8 -*-
"""
author      : 蛙鳜鸡鹳狸猿
create_time : 2017年 01月 01日 星期日 00:11:00 CST
program     : *_* script to transform IP to specific geographic position *_*
"""


import json
import urllib
import urllib2


class Location_Sina():
    """
    Interface of sina
    Under my test is of higher recognition and performance at home
    """
    def __init__(self, ip):
        self.ip = urllib.quote_plus(ip)
        self.api_url = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=%s' % self.ip

    def get_geoinfo(self):
        urlobj = urllib2.urlopen(self.api_url)
        data = urlobj.read()[20:][:-1]
        datadict = json.loads(data, encoding='utf-8')
        return datadict

    def get_country(self):
        datadict = self.get_geoinfo()
        return datadict['country']

    def get_province(self):
        datadict = self.get_geoinfo()
        return datadict['province']

    def get_city(self):
        datadict = self.get_geoinfo()
        return datadict['city']


class Location_Taobao():
    """
    Interface of taobao
    Under my test can be the 2ed choice
    """
    def __init__(self, ip):
        self.ip = urllib.quote_plus(ip)
        self.api_url = 'http://ip.taobao.com/service/getIpInfo.php?ip=%s' % self.ip

    def get_geoinfo(self):
        urlobj = urllib2.urlopen(self.api_url)
        data = urlobj.read()
        datadict = json.loads(data, encoding='utf-8')
        return datadict['data']

    def get_country(self):
        datadict = self.get_geoinfo()
        return datadict['country']

    def get_province(self):
        datadict = self.get_geoinfo()
        return datadict['region']

    def get_city(self):
        datadict = self.get_geoinfo()
        return datadict['city']

    def get_isp(self):
        datadict = self.get_geoinfo()
        return datadict['isp']


class Location_Freegeoip():
    """
    Interface of an excellent foreign service freegeoip
    The only shortage may be it return result in English
    """
    def __init__(self, ip):
        self.ip = urllib.quote_plus(ip)
        self.api_url = 'http://freegeoip.net/json/%s' % (self.ip)

    def get_geoinfo(self):
        urlobj = urllib2.urlopen(self.api_url)
        data = urlobj.read()
        datadict = json.loads(data, encoding='utf-8')
        return datadict

    def get_country(self):
        datadict = self.get_geoinfo()
        return datadict['country_name']

    def get_province(self):
        datadict = self.get_geoinfo()
        return datadict['region_name']

    def get_city(self):
        datadict = self.get_geoinfo()
        return datadict['city']


def ip2loc(ip):
    """
    An integrated user defined function via three APIs to transform IP to specific geographic position
    :param ip:IP
    :return:a list of ["country(or other)", "province(or other)", "city(or other)"]
    """
    try:
        LOC = Location_Sina(ip)
        loc = [LOC.get_country(), LOC.get_province(), LOC.get_city()]
        if all(loc): pass
        else:
            for i in range(len(loc)):
                if loc[i]: pass
                else:
                    LT_ = Location_Taobao(ip)
                    if   i == 0: loc[i] = LT_.get_country()
                    elif i == 1: loc[i] = LT_.get_province()
                    elif i == 2: loc[i] = LT_.get_city()
            if all(loc): pass
            else:
                for j in range(len(loc)):
                    if loc[j]: pass
                    else:
                        LF_ = Location_Freegeoip(ip)
                        if   j == 0: loc[j] = LF_.get_country()
                        elif j == 1: loc[j] = LF_.get_province()
                        elif j == 2: loc[j] = LF_.get_city()
                if all(loc): pass
                else:
                    for k in range(len(loc)):
                        if    loc[k]: pass
                        else: loc[k] = "暂未识别"
        return loc
    except:
        loc = ["无法处理", "无法处理", "无法处理"]
        return loc


if __name__ == '__main__':
    ip = '127.0.0.1'

    # Location_Sina
    # iploc = Location_Sina(ip)
    # print iploc.get_geoinfo()
    # print iploc.get_country()
    # print iploc.get_province()
    # print iploc.get_city()

    # Location_Taobao
    # iploc = Location_Taobao(ip)
    # print iploc.get_geoinfo()
    # print iploc.get_country()
    # print iploc.get_province()
    # print iploc.get_city()
    # print iploc.get_isp()

    # Location_Freegeoip
    # iploc = Location_Freegeoip(ip)
    # print iploc.get_geoinfo()
    # print iploc.get_country()
    # print iploc.get_province()
    # print iploc.get_city()

    # ip2loc
    loc = ip2loc(ip)
    print(loc)
    print(loc[0])
    print(loc[1])
    print(loc[2])

     对于IP地址的转换工作,最主要的是关注最后的识别率。个人以自己环境的测试结果为基础,最终选用了新浪、淘宝和国外的Freegeoip三个接口,然后以这三个接口写了一个“ip2loc”函数,确保只要传入一个IP,都能返回一个结果。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值