IP地址位置查询,通过网上的公共接口查询个人IP地址信息 网上有公布一些免费的IP地址信息查询的接口,我们可以通过这些接口获取我们想查询的IP地址信息
参考:http://blog.youkuaiyun.com/feixiangdexin123087/article/details/9058263
首先创建个文件ipCheck.py
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import re
import urllib2
这里我用的是新浪的API,因为是get请求,所以我把除ip以外的数据放到接口里了,当然你也可以不这样做
SEARCH_API = 'http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip='
ip = '58.222.254.11'
request = urllib2.Request(SEARCH_API + '%s' % str(ip))
request.add_header('Referer', 'http://int.dpool.sina.com.cn')
request.add_header('User-Agent','Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.87 Safari/537.36')
response = urllib2.urlopen(request, timeout=30)
content = response.read()
print content
var remote_ip_info = {“ret”:1,”start”:-1,”end”:-1,”country”:”\u4e2d\u56fd”,”province”:”\u6c5f\u82cf”,”city”:”\u6cf0\u5dde”,”district”:”“,”isp”:”“,”type”:”“,”desc”:”“};
这里可以看到返回的结果,发现返回的接口有unicode格式的字符串,需要转换成中文
通过正则把需要的信息提取出来
if content:
data = {}
content = re.search(r'\{.*\}', content, re.I | re.M).group()
content = content.replace('{', '')
content = content.replace('}', '')
content = content.replace('"', '')
content = list(content.split(','))
for i in range(0, len(content)):
key = str(content[i].split(':')[0])
value = str(content[i].split(':')[1])
data[key] = value
#重点讲下这里,unicode格式的字符串要先转成unicode编码,最后在通过encode('utf-8')转换成中文
country = data['country'].decode('unicode-escape')
province = data['province'].decode('unicode-escape')
city = data['city'].decode("unicode-escape")
print '\tcountry:', country.encode('utf-8')
print '\tprovince:', province.encode('utf-8')
print '\tcity:', city.encode('utf-8')
else:
print '\tFAILED'
country: 中国
province: 江苏
city: 泰州