python使用在线API查询IP对应的地理位置信息实例
这篇文章中的内容是来源于去年我用美国的VPS搭建博客的初始阶段,那是有很多恶意访问,我就根据accesslog中的源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-*-
"""
CreatedonOct20,2013
@summary:geographyinfoaboutanIPaddress
@author:Jay<smile665@gmail.com>http://smilejay.com/
"""
importjson,urllib2
importre
fromseleniumimportwebdriver
fromselenium.webdriver.common.desired_capabilitiesimportDesiredCapabilities
classlocation_freegeoip():
"""
buildthemappingoftheipaddressanditslocation.
thegeoinfoisfrom<freegeoip.net>
"""
def__init__(self,ip):
"""
Constructoroflocation_freegeoipclass
"""
self.ip=ip
self.api_format="json"
self.api_url="http://freegeoip.net/%s/%s"%(self.api_format,self.ip)
defget_geoinfo(self):
"""getthegeoinfofromtheremoteAPI.
returnadictaboutthelocation.
"""
urlobj=urllib2.urlopen(self.api_url)
data=urlobj.read()
datadict=json.loads(data,encoding="utf-8")
#printdatadict
returndatadict
defget_country(self):
key="country_name"
datadict=self.get_geoinfo()
returndatadict[key]
defget_region(self):
key="region_name"
datadict=self.get_geoinfo()
returndatadict[key]
defget_city(self):
key="city"
datadict=self.get_geoinfo()
returndatadict[key]
classlocation_taobao():
"""
buildthemappingoftheipaddressanditslocation
thegeoinfoisfromTaobao
e.g.http://ip.taobao.com/service/getIpInfo.php?ip=112.111.184.63
ThegetIpInfoAPIfromTaobaoreturnsaJSONobject.
"""
def__init__(self,ip):
self.ip=ip
self.api_url="http://ip.taobao.com/service/getIpInfo.php?ip=%s"%self.ip
defget_geoinfo(self):
"""getthegeoinfofromtheremoteAPI.
returnadictaboutthelocation.
"""
urlobj=urllib2.urlopen(self.api_url)
data=urlobj.read()
datadict=json.loads(data,encoding="utf-8")
#printdatadict
returndatadict["data"]
defget_country(self):
key=u"country"
datadict=self.get_geoinfo()
returndatadict[key]
defget_region(self):
key="region"
datadict=self.get_geoinfo()
returndatadict[key]
defget_city(self):
key="city"
datadict=self.get_geoinfo()
returndatadict[key]
defget_isp(self):
key="isp"
datadict=self.get_geoinfo()
returndatadict[key]
classlocation_qq():
"""
buildthemappingoftheipaddressanditslocation.
thegeoinfoisfromTencent.
Note:thecontentoftheTencent"sAPIreturnpageisencodedby"gb2312".
e.g.http://ip.qq.com/cgi-bin/searchip?searchip1=112.111.184.64
"""
def__init__(self,ip):
"""
Constructionoflocation_ipdotcnclass.
"""
self.ip=ip
self.api_url="http://ip.qq.com/cgi-bin/searchip?searchip1=%s"%ip
defget_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)
ifm!=None:
returnm.group(1).split(" ")
else:
returnNone
defget_region(self):
returnself.get_geoinfo()[0]
defget_isp(self):
returnself.get_geoinfo()[1]
classlocation_ipdotcn():
"""
buildthemappingoftheipaddressanditslocation.
thegeoinfoisfromwww.ip.cn
needtousePhantomJStoopentheURLtorenderitsJS
"""
def__init__(self,ip):
"""
Constructionoflocation_ipdotcnclass.
"""
self.ip=ip
self.api_url="http://www.ip.cn/%s"%ip
defget_geoinfo(self):
dcap=dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"]=(
"Mozilla/5.0(Macintosh;IntelMacOSX10.9;rv:25.0)Gecko/20100101Firefox/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()
returnres
defget_region(self):
returnself.get_geoinfo()[0]
defget_isp(self):
returnself.get_geoinfo()[1]
if__name__=="__main__":
ip="110.84.0.129"
#iploc=location_taobao(ip)
#printiploc.get_geoinfo()
#printiploc.get_country()
#printiploc.get_region()
#printiploc.get_city()
#printiploc.get_isp()
#iploc=location_qq(ip)
iploc=location_ipdotcn(ip)
#iploc.get_geoinfo()
printiploc.get_region()
printiploc.get_isp()
相关文章
- python求逆矩阵的方法,Python 如何求矩阵的逆「建议收藏」
- python中if __name__ == ‘__main__’是什么意思
- python中关于命名的例子_Python 命名规范入门实例「建议收藏」
- pycharm pro 2022 for mac(Python编辑开发)v2022.2.2中文激活版
- Python: “淘宝商品比价定向爬虫”实例
- python表情代码_Python实现表情包的代码实例[通俗易懂]
- python os 模拟实现创建用户
- 【说站】python类变量和实例变量的对比
- 【测试开发】python系列教程: 标准数据类型(二)字符串
- python分析人口出生率代码_国家统计局居然也能用的上Python?人口数据Python脚本了解一下?…[通俗易懂]
- Python:利用python代码编程实现将视频的avi格式转换为MP4格式
- python递归函数讲解_Python递归函数实例讲解
- 编译成功了,运行为什么会失败_cython编译python
- Python 自动化系统信息收集
- python高级线程编程-线程间通信(二)
- ChatGPT帮我写Python + pytest + selenium框架
- Python类调用实例方法
- python获取Windows特殊文件夹路径代码详解编程语言
- Bash vs Python:你该使用哪个?
- Linux下运行Python脚本的步骤简介(linux如何运行python脚本)
- Python与MySQL实现数据分析的完美组合(mysql中python)
- python用Redis与Python实现大数据收集与分析(redis 联合)
- 用实例说明python的*args和**kwargs用法
- python算法学习之桶排序算法实例(分块排序)
- python数据结构之二叉树的遍历实例
- 零基础写python爬虫之使用Scrapy框架编写爬虫
- Python多进程同步Lock、Semaphore、Event实例
- python多线程操作实例
- Python中模拟enum枚举类型的5种方法分享
- python静态方法实例