python使用在线API查询IP对应的地理位置信息实例
发布时间:2021-12-10 23:59:16
这篇文章中的内容是来源于去年我用美国的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(' ')
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()
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- 本文为大家分享了Python遗传算法解决最大流问题,供大家参考,具体内容如下Generate_matrixdef Generate_matr
- 要想从命令行启动mysqld服务器,你应当启动控制台窗口(或“DOS window”)并输入命令:C
- 一、时间获取函数>>> import time>>> time.time()1570530861.740
- 本文实例讲述了PHP基于phpqrcode生成带LOGO图像的二维码。分享给大家供大家参考。具体如下:这里PHP使用phpqrcode生成带
- 在利用tensorflow进行文本挖掘工作的时候,经常涉及到维度扩展和压缩工作。比如对文本进行embedding操作完成之后,若要进行卷积操
- 可匹配单行,也支持换行匹配[\s\S]*?加上括号,效果更好([\s\S]*?)来源:https://blog.csdn.net/ASUKA
- IE6下浮出层常会需要增加一个iframe来解决浮出层被Obj穿透的问题,这个是目前最有效的方案,不过这个方案本身有个缺陷,就是iframe
- 在网站建设中,分类算法的应用非常的普遍。在设计一个电子商店时,要涉及到商品分类;在设计发布系统时,要涉及到栏目或者频道分类;在设计软件下载这
- 观察者模式结构图概念一个"演员"(被观察者),一群"观众"(观察者),一台"摄影机&quo
- 1. 匿名函数匿名函数(anonymous function)是指未与任何标识符绑定的函数,多用在functional programmin
- 灰度直方图概括了图像的灰度级信息,简单的来说就是每个灰度级图像中的像素个数以及占有率,创建直方图无外乎两个步骤,统计直方图数据,再用绘图库绘
- 一,PHP脚本与动态页面。 PHP脚本是一种服务器端脚本程序,可通过嵌入等方 法与HTML文件混合,也可以类,函数封
- 今天在群(CSS森林:30247792)里讨论了border的样式写法,发现border的写法还真是灵活,做了一下总结,希望对大家有用:bo
- 问题你的包中包含代码需要去读取的数据文件。你需要尽可能地用最便捷的方式来做这件事。解决方案假设你的包中的文件组织成如下:mypackage/
- 今天遇到一个需要用javascript将url中的某些参数替换的需求,想起了不久前从网上淘到了一个parseUrl函数,正好可以借此实现,代
- 前言cookie:在网站中,http请求是无状态的。也就是说即使第一次和服务器连接后并且登录成功后,第二次请求服务器依然不能知道当前请求是哪
- 编解码器在字符与字节之间的转换过程称为编解码,Python自带了超过100种编解码器,比如:ascii(英文体系)gb2312(中文体系)u
- 使用python实现简单倒计时exe,供大家参考,具体内容如下使用tkinter制作界面实现倒计时功能。使用time.sleep(1)实现
- 本文实例讲述了Python编程判断这天是这一年第几天的方法。分享给大家供大家参考,具体如下:题目:输入某年某月某日,判断这一天是这一年的第几
- 1.什么是labelpandas处理数据时,我们会经常看到dataframe结构使用loc, iloc, ix等方法。那么这些方法到底有啥区