国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

python使用在線API查詢IP對應(yīng)的地理位置信息實例

2019-11-25 18:24:18
字體:
供稿:網(wǎng)友

這篇文章中的內(nèi)容是來源于去年我用美國的VPS搭建博客的初始階段,那是有很多惡意訪問,我就根據(jù)access log中的源IP來進行了很多統(tǒng)計,同時我也將訪問量最高的惡意訪問的源IP拿來查詢其地理位置信息。所以,我就用到了根據(jù)IP查詢地理位置信息的一些東西,現(xiàn)在將這方面積累的一點東西共享出來。

根據(jù)IP查詢所在地、運營商等信息的一些API如下(根據(jù)我有限的一點經(jīng)驗):
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 這個還提供了經(jīng)緯度信息(但不一定準)
3. 新浪的API:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=110.84.0.129
4. 騰訊的網(wǎng)頁查詢:http://ip.qq.com/cgi-bin/searchip?searchip1=110.84.0.129
5. ip.cn的網(wǎng)頁: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的網(wǎng)站和IP數(shù)據(jù)的生成,代碼在:https://github.com/fiorix/freegeoip)

為什么其中第4、5兩個是網(wǎng)頁查詢也推薦了呢?是因為兩方面原因,一是它們提供的信息比較準,二是使用了頁面信息自動抓取(可能會用到我曾經(jīng)寫過的PhantomJS)也容易將其寫到程序中成為API。

根據(jù)IP查詢地理位置信息,我將其寫成了一個較為通用的Python庫(提供了前面提到的1、2、4、5等4種查詢方式的API),可以根據(jù)IP查詢到地域信息和ISP信息,具體代碼見:
https://github.com/smilejay/python/blob/master/py2013/iplocation.py
注意其中對ip.cn網(wǎng)頁的解析用到了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(' ')
        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()

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 惠来县| 凌云县| 甘孜| 青冈县| 阳西县| 通许县| 莎车县| 新龙县| 铁力市| 南澳县| 舟曲县| 沛县| 五大连池市| 平度市| 南乐县| 泸溪县| 磐石市| 芮城县| 时尚| 和顺县| 德令哈市| 玛曲县| 连城县| 卢龙县| 聊城市| 织金县| 左权县| 正蓝旗| 林州市| 洛宁县| 苏尼特右旗| 乐清市| 资源县| 韶山市| 香格里拉县| 磐安县| 白水县| 安陆市| 镇原县| 固始县| 策勒县|