您的位置:首页 > 编程语言 > Python开发

python分析ip地理位置-python3版本

2012-08-28 16:21 211 查看
原帖为python2.6写的/article/4290508.html

看到一网友用python2.6写的一个脚本,处于好奇将其改写为python3,并做了小小的改动,在python3.2.3+win7及python3.2.2+SLES11 SP1下测试通过

#!/usr/bin/env  python
import  sys
import  http
import  http.client
import  urllib
import  re

#http://www.ip138.com/ips1388.asp?ip=112.254.67.142&action=2
if len(sys.argv) < 3:
print("NO ip file found\nusage: python checkip.py  ip.txt result.txt")
sys.exit()

web_url="www.ip138.com"
u1="/ips1388.asp?ip="
u2="218.31.158.174"
u3="&action=2"
fd=open(sys.argv[1],"r")
#print("sys.argv[1]:",sys.argv[1])
result=open(sys.argv[2],"w")
for  line  in  fd.readlines():
#print("line:",line)
geturl=u1+line.strip()+u3
#print("url:",geturl)
conn=http.client.HTTPConnection(web_url)
conn.request("GET",geturl)
r1=conn.getresponse()
#print("status:",r1.status)
data1=r1.read()
#forma=sys.getfilesystemencoding()
html=data1.decode("gbk")
keyword=re.compile(r'''<td align="center"><ul class="ul1"><li>(.*?)</li><li>''', re.U|re.S)
a=re.findall(keyword,html)
#print("length:",len(a))
#print(a)
#print(type(a))
s=line.strip() + "\t\t\t" + a[0]+"\n"
if len(a)>0:
print(s)
result.write(s)

else:
print("Maybe have not web content")
conn.close()

fd.close()
result.flush()
result.close()


执行:

python  checkip.py  ip.txt  result.txt


result文件如下:

119.128.200.90 本站主数据:广东省东莞市 电信

218.90.169.90 本站主数据:江苏省无锡市 电信

219.129.242.180 本站主数据:广东省韶关市 电信

183.69.189.172 本站主数据:重庆市 电信

222.89.193.18 本站主数据:河南省平顶山市 电信

221.193.222.105 本站主数据:河北省邯郸市 联通

59.151.213.135 本站主数据:韩国

218.22.182.50 本站主数据:安徽省铜陵市 电信

124.238.192.23 本站主数据:湖北省武汉市 长城宽带

113.111.94.116 本站主数据:广东省广州市 电信

115.182.53.30 本站主数据:北京市 电信通
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: