用python测试url
本帖最后由 LSA 于 2017-3-24 16:13 编辑前段时间在找google镜像站的时候,找到很多但是有些是失效的有些响应很慢,于是写了一个python脚本来测试收集到的镜像站的速度,这是v1.0版还有一些不足,不过能基本满足测试url的需求,有空再完善。
功能描述:测试url能否打开并且利用ping测试响应速度,最后统计出响应速度前3快的url,对于一些能打开但是ping不通的url(可能防火墙阻挡)另外统计。
效果图:
代码打包:
代码展示:
#coding:gb2312
#description:check urls and test ping average speed
#author:LSA
#Date:20170218
import urllib2,time
import subprocess
import re
import optparse
#from threading import Thread
global count0,count1,count2
count0 = 0
count1 = 0
count2 = 0
global urlave
urlave = {}
global aves
aves = []
global speurls
speurls = []
notping = 'Can not ping but can open!'
def ping_ave_speed(tempUrl):
global speurls
pingtempUrl = tempUrl.split('/')
p = subprocess.Popen(["ping.exe",pingtempUrl],
stdin = subprocess.PIPE,
stdout = subprocess.PIPE,
stderr = subprocess.PIPE,
shell = True)
out = p.stdout.read()
reg = re.compile("平均 = (\d+)ms", re.IGNORECASE)
if not reg.findall(out):
speurls.append(tempUrl)
return str(10000)
else:
return str(reg.findall(out))
def test_url(fname):
global count0
global count1
global count2
global aves
global urlave
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/49.0.2')]
file0 = open(fname)
lines = file0.readlines()
urls = []
for line in lines:
temp = line.replace('\n','')
urls.append(temp)
count0 = count0 + 1
print 'Beginning check urls:'
for url in urls:
tempUrl = url
count1 = count1 + 1
try :
opener.open(tempUrl)
ave = ping_ave_speed(tempUrl)
aves.append(int(ave))
urlave = tempUrl
print tempUrl+'---normal'+'('+str(count1)+'/'+str(count0)+')'
count2 = count2 + 1
except urllib2.HTTPError:
print tempUrl+'---failed('+str(count1)+'/'+str(count0)+')'
time.sleep(1)
except urllib2.URLError:
print tempUrl+'---failed('+str(count1)+'/'+str(count0)+')'
time.sleep(1)
time.sleep(0.1)
aves.sort()
file0.close()
if __name__=='__main__':
Usage = "%prog -f <urlfile>"
parser = optparse.OptionParser(Usage,version="%prog v1.0")
parser.add_option('-f',dest='fname',type='string',help='input a urls file name')
(options,args) = parser.parse_args()
if(options.fname == None):
print parser.usage
exit(0)
else:
fname = options.fname
test_url(fname)
print '===========Statistics==========='
print 'Total check: '+str(count0)+' urls,'+'normal: '+str(count2)+' url'
print urlave]+')+']'+'---1'
print urlave]+')+']'+'---2'
print urlave]+')+']'+'---3'
print '-----------'
print notping
for speurl in speurls:
print speurl
厉害厉害谢谢分享 厉害,收走了,很有帮助。 如何回报帮助你解决问题的坛友,一个好办法就是给对方加【热心】和【CB】,加分不会扣除自己的积分,做一个热心并受欢迎的人! 感谢分享
页:
[1]