01.import socket 02.import time 03.timeout = 20 04.socket.setdefaulttimeout(timeout)#这里对整个socket层设置超时时间。后续文件中如果再使用到socket,不必再设置 05.sleep_download_time = 10 06.time.sleep(sleep_download_time) #这里时间自己设定 07.request = urllib.request.urlopen(url)#这里是要读取内容的url 08.content = request.read()#读取,一般会在这里报异常 09.request.close()#记得要关闭
try:
time.sleep(self.sleep_download_time)
request = urllib.request.urlopen(url)
content = request.read()
request.close()
except UnicodeDecodeError as e:
print('-----UnicodeDecodeError url:',url)
except urllib.error.URLError as e:
print("-----urlError url:",url)
except socket.timeout as e:
print("-----socket timout:",url)
def Download_auto(downloadlist,fun,sleep_time=15):
while True:
try: # 外包一层try
value = fun(downloadlist,sleep_time) # 这里的fun是你的下载函数,我当函数指针传进来。
# 只有正常执行方能退出。
if value == Util.SUCCESS:
break
except : # 如果发生了10054或者IOError或者XXXError
sleep_time += 5 #多睡5秒,重新执行以上的download.因为做了检查点的缘故,上面的程序会从抛出异常的地方继续执行。防止了因为网络连接不稳定带来的程序中断。
print('enlarge sleep time:',sleep_time)
# 打印下载信息
def reporthook(blocks_read, block_size, total_size):
if not blocks_read:
print ('Connection opened')
if total_size < 0:
print ('Read %d blocks' % blocks_read)
else:
# 如果找不到,页面不存在,可能totalsize就是0,不能计算百分比
print('downloading:%d MB, totalsize:%d MB' % (blocks_read*block_size/1048576.0,total_size/1048576.0))
def Download(path,url):
#url = 'http://downloads.sourceforge.net/sourceforge/alliancep2p/Alliance-v1.0.6.jar'
#filename = url.rsplit("/")[-1]
try:
# python自带的下载函数
urllib.request.urlretrieve(url, path, reporthook)
except IOError as e: # 如果找不到,好像会引发IOError。
print("download ",url,"/nerror:",e)
print("Done:%s/nCopy to:%s" %(url,path))
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有