這篇文章中的內容是來源于去年我用美國的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.
新聞熱點
疑難解答