python使用在线API查询IP对应的地理位置信息实例

 更新时间:2014年06月01日 22:29:05   作者:  
这篇文章主要介绍了python使用在线API查询IP对应的地理位置信息实例,需要的朋友可以参考下

这篇文章中的内容是来源于去年我用美国的VPS搭建博客的初始阶段,那是有很多恶意访问,我就根据access log中的源IP来进行了很多统计,同时我也将访问量最高的恶意访问的源IP拿来查询其地理位置信息。所以,我就用到了根据IP查询地理位置信息的一些东西,现在将这方面积累的一点东西共享出来。

根据IP查询所在地、运营商等信息的一些API如下(根据我有限的一点经验):
1. 淘宝的API(推荐):http://ip.taobao.com/service/getIpInfo.php?ip=110.84.0.129
2. 国外freegeoip.net(推荐):http://freegeoip.net/json/110.84.0.129 这个还提供了经纬度信息(但不一定准)
3. 新浪的API:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=110.84.0.129
4. 腾讯的网页查询:http://ip.qq.com/cgi-bin/searchip?searchip1=110.84.0.129
5. ip.cn的网页:http://www.ip.cn/index.php?ip=110.84.0.129
6. ip-api.com: http://ip-api.com/json/110.84.0.129 (看起来挺不错的,貌似直接返回中文城市信息,文档在 ip-api.com/docs/api:json)
7. http://www.locatorhq.com/ip-to-location-api/documentation.php (这个要注册才能使用,还没用过呢)

(第2个freegeoip.net的网站和IP数据的生成,代码在:https://github.com/fiorix/freegeoip)

为什么其中第4、5两个是网页查询也推荐了呢?是因为两方面原因,一是它们提供的信息比较准,二是使用了页面信息自动抓取(可能会用到我曾经写过的PhantomJS)也容易将其写到程序中成为API。

根据IP查询地理位置信息,我将其写成了一个较为通用的Python库(提供了前面提到的1、2、4、5等4种查询方式的API),可以根据IP查询到地域信息和ISP信息,具体代码见:
https://github.com/smilejay/python/blob/master/py2013/iplocation.py
注意其中对ip.cn网页的解析用到了webdriver和PhantomJS.

复制代码 代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-

'''
Created on Oct 20, 2013
@summary: geography info about an IP address
@author: Jay <smile665@gmail.com> http://smilejay.com/
'''

import json, urllib2
import re
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

 
class location_freegeoip():
    '''
build the mapping of the ip address and its location.
the geo info is from <freegeoip.net>
'''

    def __init__(self, ip):
        '''
Constructor of location_freegeoip class
'''
        self.ip = ip
        self.api_format = 'json'
        self.api_url = 'http://freegeoip.net/%s/%s' % (self.api_format, self.ip)

    def get_geoinfo(self):
        """ get the geo info from the remote API.
return a dict about the location.
"""
        urlobj = urllib2.urlopen(self.api_url)
        data = urlobj.read()
        datadict = json.loads(data, encoding='utf-8')
# print datadict
        return datadict

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

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

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

class location_taobao():
    '''
build the mapping of the ip address and its location
the geo info is from Taobao
e.g. http://ip.taobao.com/service/getIpInfo.php?ip=112.111.184.63
The getIpInfo API from Taobao returns a JSON object.
'''
    def __init__(self, ip):
        self.ip = ip
        self.api_url = 'http://ip.taobao.com/service/getIpInfo.php?ip=%s' % self.ip

    def get_geoinfo(self):
        """ get the geo info from the remote API.
return a dict about the location.
"""
        urlobj = urllib2.urlopen(self.api_url)
        data = urlobj.read()
        datadict = json.loads(data, encoding='utf-8')
# print datadict
        return datadict['data']

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

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

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

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

 
class location_qq():
    '''
build the mapping of the ip address and its location.
the geo info is from Tencent.
Note: the content of the Tencent's API return page is encoded by 'gb2312'.
e.g. http://ip.qq.com/cgi-bin/searchip?searchip1=112.111.184.64
'''
    def __init__(self, ip):
        '''
Construction of location_ipdotcn class.
'''
        self.ip = ip
        self.api_url = 'http://ip.qq.com/cgi-bin/searchip?searchip1=%s' % ip

    def get_geoinfo(self):
        urlobj = urllib2.urlopen(self.api_url)
        data = urlobj.read().decode('gb2312').encode('utf8')
        pattern = re.compile(r'该IP所在地为:<span>(.+)</span>')
        m = re.search(pattern, data)
        if m != None:
            return m.group(1).split('&nbsp;')
        else:
            return None

    def get_region(self):
        return self.get_geoinfo()[0]

    def get_isp(self):
        return self.get_geoinfo()[1]

 
class location_ipdotcn():
    '''
build the mapping of the ip address and its location.
the geo info is from www.ip.cn
need to use PhantomJS to open the URL to render its JS
'''
    def __init__(self, ip):
        '''
Construction of location_ipdotcn class.
'''
        self.ip = ip
        self.api_url = 'http://www.ip.cn/%s' % ip

    def get_geoinfo(self):
        dcap = dict(DesiredCapabilities.PHANTOMJS)
        dcap["phantomjs.page.settings.userAgent"] = (
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0) Gecko/20100101 Firefox/29.0 " )
        driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs', desired_capabilities=dcap)
        driver.get(self.api_url)
        text = driver.find_element_by_xpath('//div[@id="result"]/div/p').text
        res = text.split('来自:')[1].split(' ')
        driver.quit()
        return res

    def get_region(self):
        return self.get_geoinfo()[0]

    def get_isp(self):
        return self.get_geoinfo()[1]

 
if __name__ == '__main__':
    ip = '110.84.0.129'
# iploc = location_taobao(ip)
# print iploc.get_geoinfo()
# print iploc.get_country()
# print iploc.get_region()
# print iploc.get_city()
# print iploc.get_isp()
# iploc = location_qq(ip)
    iploc = location_ipdotcn(ip)
# iploc.get_geoinfo()
    print iploc.get_region()
    print iploc.get_isp()

相关文章

  • minconda安装pytorch的详细方法

    minconda安装pytorch的详细方法

    这篇文章主要介绍了minconda安装pytorch的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • python numpy库介绍

    python numpy库介绍

    这篇文章主要介绍了python numpy库,numpy是一个开源的python科学计算扩展库,主要用来处理任意维度数组和矩阵。相同的任务,使用numpy比直接用python的基本数据结构更加简单高效,下面一起进入文章了解更多详细内容吧
    2021-12-12
  • python人工智能tensorflow函数tf.get_variable使用方法

    python人工智能tensorflow函数tf.get_variable使用方法

    这篇文章主要为大家介绍了python人工智能tensorflow函数tf.get_variable使用方法示例,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-05-05
  • Python命令行定时任务自动化工作流程

    Python命令行定时任务自动化工作流程

    本文介绍如何使用Python编写定时任务,以自动执行命令行任务。您将学习如何安排定期的任务,处理任务结果,以及如何使用Python自动化工作流程,从而提高工作效率。无需手动执行重复任务,Python帮您搞定
    2023-04-04
  • python3 map函数和filter函数详解

    python3 map函数和filter函数详解

    这篇文章主要介绍了python3 map函数和filter函数详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • Python实现为图片添加水印的示例详解

    Python实现为图片添加水印的示例详解

    这篇文章主要介绍了如何通过Python3实现添加水印,这样发朋友圈,图片再也不怕被盗了!!!文中的示例代码简洁易懂,需要的可以参考一下
    2022-02-02
  • Python collections.defaultdict模块用法详解

    Python collections.defaultdict模块用法详解

    这篇文章主要介绍了Python collections.defaultdict模块用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-06-06
  • Python调用工具包实现发送邮件服务

    Python调用工具包实现发送邮件服务

    这篇文章主要为大家详细介绍了Python图画调用工具包实现发送邮件服务的功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-05-05
  • 详解opencv Python特征检测及K-最近邻匹配

    详解opencv Python特征检测及K-最近邻匹配

    这篇文章主要介绍了详解opencv Python特征检测及K-最近邻匹配,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2019-01-01
  • Python完成哈夫曼树编码过程及原理详解

    Python完成哈夫曼树编码过程及原理详解

    这篇文章主要介绍了Python完成哈夫曼树编码过程及原理详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07

最新评论