Python uses an online API to query IP-corresponding geographic information instances _python

Source: Internet
Author: User
Tags dcap

This article is based on the initial phase of my blog, which I used to build a U.S. VPS last year, that is a lot of malicious access, I based on access log in the source IP to do a lot of statistics, and I also have the most visited the most malicious access to the source IP to query its geographic location information. So, I used the IP query based on the location of some things, and now the accumulation of a little something in the shared out.

According to the IP query location, operators and other information on some of the APIs below (based on my limited experience):
1. Taobao API (recommended): http://ip.taobao.com/service/getIpInfo.php?ip=110.84.0.129
2. Foreign freegeoip.net (recommended): http://freegeoip.net/json/110.84.0.129 This also provides latitude and longitude information (but not necessarily)
3. Sina's api:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=110.84.0.129
4. Tencent's Web search: http://ip.qq.com/cgi-bin/searchip?searchip1=110.84.0.129
5. Ip.cn's Web page: http://www.ip.cn/index.php?ip=110.84.0.129
6. ip-api.com:http://ip-api.com/json/110.84.0.129 (looks very good, seemingly directly returned to the Chinese city information, documents in Ip-api.com/docs/api:json)
7. http://www.locatorhq.com/ip-to-location-api/documentation.php (this is to register to use, still not used it)

(2nd freegeoip.net Web site and generation of IP data, code in: HTTPS://GITHUB.COM/FIORIX/FREEGEOIP)

Why are the 4th and 52 of them Web queries also recommended? Because of two reasons, one is that they provide more accurate information, the second is to use the page information automatically crawl (may use the PHANTOMJS I have written) also easy to write it into the program into the API.

Based on IP query location information, I wrote it a more general Python library (provides the aforementioned 1, 2, 4, 5, etc. 4 query methods of the API), can be based on IP query to geographical information and ISP information, specific code see:
https://github.com/smilejay/python/blob/master/py2013/iplocation.py
Note that the parsing of ip.cn Web pages uses Webdriver and PHANTOMJS.

Copy Code code as follows:

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

'''
Created on Oct 20, 2013
@summary: Geography info about 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 addresses and its location.
The GEO info are 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's 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 addresses 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 ' This IP location is:<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 addresses and its location.
The GEO info is from www.ip.cn
Need to the "PHANTOMJS" to "open" 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 (' From: ') [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 ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.