Get Region Information from IP Address with Taobao API
通过淘宝的API "http://ip.taobao.com/service/getIpInfo.php?ip=*.*.*.*" 来获得你要查询的IP地址的国家,地区,城市,ISP等
地理位置信息.
Python代码如下:
#!/usr/bin/python2.7 #File: IP2Region.py #Author: lxw #Time: 2014-12-03 #Usage: Get the location information from IP. #Reference:http://smilejay.com/2014/05/python-get-geoinfo-from-ip/ #The data format that location_taobao.getLocation() returns is as follow: #{ # "code":0, # "data":{ # "country":"\u53f0\u6e7e", # "country_id":"TW", # "area":"", # "area_id":"", # "region":"\u53f0\u6e7e\u7701", # "region_id":"TW_01", # "city":"", # "city_id":"", # "county":"", # "county_id":"", # "isp":"", # "isp_id":"-1", # "ip":"218.211.14.165" # } #} import json import urllib2 class location_taobao(object): ''' Build the map of IP and its location. The location info is from Taobao e.g. http://ip.taobao.com/service/getIpInfo.php?ip=218.211.14.165 The getIpInfo API from Taobao returns a JSON object. ''' def __init__(self, ip): self.ip = ip self.url = "http://ip.taobao.com/service/getIpInfo.php?ip={0}".format(self.ip) #NOTE: OK. #Call another method in the CONSTRUCTOR(__init__()). self.location = self.getLocation() def getLocation(self): ''' Get the location info from self.url. The location info are involved in the JSON object returned. ''' #"urlopen()" is like the built-in function "open()" for "file". urlobj = urllib2.urlopen(self.url) data = urlobj.read() #str dataDict = json.loads(data, encoding="utf-8") # dict return dataDict["data"] #The type of dataDict["data"] is still dict. def getCountry(self): #self.location can be str("invalid Ip") or dict. try: result = self.location.get(u"country") except: pass else: return result def getRegion(self): try: result = self.location.get(u"region") except: pass else: return result def getCity(self): try: result = self.location.get(u"city") except: pass else: return result def getISP(self): try: result = self.location.get(u"isp") except: pass else: return result def main(): while 1: ip = raw_input("Please input the IP you want to check(Input \"END\" to stop):\n") if ip == "END": break obj = location_taobao(ip) #print("Country: {0}".format(obj.getCountry())) #NOT OK. encode. print(u"Country: {0}".format(obj.getCountry())) print(u"Region: {0}".format(obj.getRegion())) print(u"City: {0}".format(obj.getCity())) print(u"ISP: {0}\n".format(obj.getISP())) if __name__ == '__main__': main() else: print("Being imported as a module.")
Reference:
python根据IP查地理位置信息: http://smilejay.com/2014/05/python-get-geoinfo-from-ip/