原文转载于https://www.cnblogs.com/kevingrace/p/5840951.html
但是直接拷贝原文的代码运行报错异常,怀疑是不同Python版本使用StringIO BytesIO导致
执行报错,直接注释了,使用下面代码可以执行出和原文一样的效果
# test_netRate.py 测试网页网速 #!/usr/bin/python # coding: UTF-8 import pycurl, sys, os, time from io import BytesIO ''' class idctest: def __init__(self): self.contents = '' def body_callback(self, buff): buff = BytesIO() self.contents = self.contents + buff ''' def test_gzip(input_url): # t = idctest() e = BytesIO() c = pycurl.Curl() #创建一个同libcurl中的CURL处理器相对应的Curl对象 # c.setopt(pycurl.WRITEFUNCTION, t.body_callback) #写的回调 c.setopt(pycurl.WRITEFUNCTION, e.write) #写的回调 c.setopt(pycurl.ENCODING, 'gzip') #编码 c.setopt(pycurl.URL, input_url) #设置要访问的网址 input_url = "http://www.baidu.com" c.setopt(pycurl.MAXREDIRS, 5) #最大重定向次数,可以预防重定向陷阱 c.perform() #执行上述访问网址的操作 http_code = c.getinfo(pycurl.HTTP_CODE) dns_resolve = c.getinfo(pycurl.NAMELOOKUP_TIME) http_conn_time = c.getinfo(pycurl.CONNECT_TIME) http_pre_trans = c.getinfo(pycurl.PRETRANSFER_TIME) http_start_trans = c.getinfo(pycurl.STARTTRANSFER_TIME) http_total_time = c.getinfo(pycurl.TOTAL_TIME) http_size_download = c.getinfo(pycurl.SIZE_DOWNLOAD) http_header_size = c.getinfo(pycurl.HEADER_SIZE) http_speed_downlaod = c.getinfo(pycurl.SPEED_DOWNLOAD) print('HTTP响应状态: %d' % http_code) print('DNS解析时间:%.2f ms' % (dns_resolve * 1000)) print('建立连接时间: %.2f ms' % (http_conn_time * 1000)) print('准备传输时间: %.2f ms' % (http_pre_trans * 1000)) print("传输开始时间: %.2f ms" % (http_start_trans * 1000)) print("传输结束时间: %.2f ms" % (http_total_time * 1000)) print("下载数据包大小: %d bytes/s" % http_size_download) print("HTTP头大小: %d bytes/s" % http_header_size) print("平均下载速度: %d k/s" % (http_speed_downlaod / 1024)) if __name__ == '__main__': input_url = sys.argv[1] test_gzip(input_url)
在控制台执行运行命令 python test_netRate.py http://www.sina.com
或者直接替换要输入的input_url