最近在做一项网关跑分测试,通过刷新网页去得到测试结果(测试结果在网页上面),这样每统计一次结果都要刷新一下页面,然后在包各项结果统计到excel中,感觉太麻烦,于是写了一个python脚本,自动刷新网页,并且将结果统计到excel中。因为网页数据格式是固定的,所以脚本思路如下:
1:首先将网页内容抓取出来,保存到一个文件中
def saveHtml(file_name, file_content): with open(file_name.replace('/', '_') + ".txt", "wb") as f: f.write(file_content) f.close()import urllib2
url = "http://192.168.1.1:8080/test"
content = urllib2.urlopen(url).read() saveHtml("jembenchtest", content)
2:查看一下关键数字在第几行,把这一行读出来
count = linecache.getline('jembenchtest.txt',10)#第十行 使用linecache模块要注意的是,如果要循环读取数据的话,每次循环需要使用import linecache
更新一下缓存,并且在循环结束后,最好使用如下命令把缓存清一下linecache.updatecache('jembenchtest.txt')
linecache.clearcache()
3:根据上一步得到的结果,通过正则运算得到想要数字
ret1 = re.search('\d+', count).group() #该行第一个匹配到的数字import re
ret2 = re.findall('\d+', count, re.M) #该行匹配到的所有数字,会放到序列里
ret2[i]#使用这种方法得到想要的第i个数字
4:将数字统计到表格中。
import xlwt #这个模块要先手动导入才能用
f = xlwt.Workbook() #创建工作簿
sheet1 = f.add_sheet(u'sheet1',cell_overwrite_ok=True) #创建sheetsheet1.write(i,j,long(ret1,base=10)) #i为行 j为列,将字符串转成十进制
f.save("jembentest.xlsx")
5:如果想在程序中打印出时间可使用如下方法
import time
print "Start time is: "+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
time.sleep(20)print "End time is: "+time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())