#!/usr/bin/env python
#coding=utf8
################################
# 通過ip138判斷ip所在地區
# 第一版
# author:xxxx
##################################
import sys
import urllib2
import urllib
import httplib
import re
'''
ip 查詢格式
http://www.ip138.com/ips8.asp?ip=112.254.67.142&action=2'''
#url = "http://www.ip138.com/ips8.asp?ip="
#ip = "112.254.67.142"
#mark = "&action=2"
#getString = url + ip + mark
#rep = urllib2.Request(getString)
#fd = urllib2.urlopen(rep)
#while 1:
#data = fd.read(1024)
#if not len(data):
#break
#print data
web_url = "www.ip138.com"
u1 = "/ips8.asp?ip="
u2 = "112.254.67.142"
u3 = "&action=2"
#getUrl = u1 + u2 + u3
fd = open('1.txt','r+')
for line in fd.readlines():
#rstrip去掉右邊空格和回車換行符
getUrl = u1 + line.rstrip() + u3
conn = httplib.HTTPConnection(web_url)
conn.request("GET", getUrl)
r1 = conn.getresponse()
data1 = r1.read()
#都是将gb2312編碼的str轉為unicode編碼
#print data1.decode('gb2312')
#keyword = re.compile(r'''<td align="center"><ul class="ul1"><li>(.*?)</li></ul></td>''', re.U|re.S)
keyword = re.compile(r'''<td align="center"><ul class="ul1"><li>(.*?)</li><li>''', re.U|re.S)
a = re.findall(keyword,data1)
print line.strip() + "\t" + a[0].decode('gb2312')
conn.close()
fd.close()
1.txt 内容如下:
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
執行上面的程式就會顯示ip的地理位置。需要python環境支援。
本文轉自 liang3391 51CTO部落格,原文連結:http://blog.51cto.com/liang3391/544754