python分析ip地理位置

2020-01-09 17:09:23 浏览数 (1)

代码语言:javascript复制
#!/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环境支持。

0 人点赞