__author__ = 'kw107301' # -*- coding: utf-8 from BeautifulSoup import BeautifulSoup from optparse import OptionParser import urllib import urllib2 import re import os def print_help(): print "Usage:python p.py <-t | --type> <0-5> <ip_address | domain>" def enter_cmd(): cmd = raw_input("Enter ? for help and Enter ping to ping:") cmd = cmd.strip().lower() return cmd def get_ret(): usage = "usage: %prog [option] arg" parser = OptionParser(usage) parser.add_option("-t","--type",default="0",help="Usage:python p.py <-t | --type> <0-5> <ip_address | domain>") (options,args) = parser.parse_args() if len(args) != 1: parser.print_help() parser.error("input the url you want to ping") """input the url""" input_url = args[0] print options,args """获取ping的线路""" opts = {} for k, v in options.__dict__.items(): opts[k] = v print opts[k] type = opts[k] type_dict = {'0':'全选','1':'电信','2':'多线','3':'联通','4':'移动','5':'海外'} """设置post数据,将选择的链路和url转为一个列表""" post_data = [] for t in type: if str(t) == "0": post_data = [('alllinetype',type_dict[str(t)])] post_data.extend([('linetype',type_dict[str(i)]) for i in xrange(1,6)]) else: post_data.append(('linetype',type_dict[str(t)])) post_data.append(('host',input_url)) print post_data """转换post_data的格式""" post_data = urllib.urlencode(post_data).encode('utf-8') """post_data = urllib.quote_plus(str(post_data))""" """发起请求""" req_url = "http://ping.chinaz.com" user_agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 Safari/537.36" headers = { 'User-Agent' : user_agent } req = urllib2.Request(req_url, post_data, headers) response = urllib2.urlopen(req) page = response.read() """创建正则匹配规则,获取返回的url""" regx = re.compile(r"iframe src='([^']*)'") s = regx.search(page) real_url = "%s%s" % (req_url,s.groups()[0]) """再次发起请求,获取ping的结果""" req2 = urllib2.Request(real_url, user_agent) responese2 = urllib2.urlopen(req2) real_ret = responese2.read() """对返回的结果运用正则进行解析""" real_ret = re.split(r'[\';]*<\/?script>[^=]+=\'?',real_ret) html = '\n'.join(real_ret) bfs = BeautifulSoup(html) litag = bfs.findAll('li') """分割列表""" for l in range(0 ,len(litag), 6): j = litag[l:l+6] print "%s\t%s\t%s\t%s\t%s" % (j[0].getText(),j[1].getText(),j[2].getText(),j[3].getText(),j[4].getText()) def main(): cmd = enter_cmd() if cmd == "?": print_help() elif cmd == "ping": get_ret() if __name__ == '__main__': main()