笔者使用的是python 3.8.6rc1,由于python3本身不支持https下载,因此需要参考这篇文章来实现https下载.
import urllib.request
import chardet
import re
import ssl
import sys
import time
steamID=input("请输入地图steamID")
page = urllib.request.urlopen('http://steamworkshop.download/download/view/'+steamID) #打开网页
htmlCode=page.read() #获取网页源码
data=htmlCode.decode('utf-8')
reg_url = re.compile(r'(?<=https://steamusercontent).*?(?=\')')
urlList=reg_url.findall(data)
for url in urlList:
downloadUrl='https://steamusercontent'+url
break
reg_name = re.compile(r'(?<=title=\').*?(?=\'>Download)')
nameList=reg_name.findall(data)
for name in nameList:
downloadName=name+'.vpk'
break
'''
urllib.urlretrieve 的回调函数:
def callbackfunc(blocknum, blocksize, totalsize):
@blocknum: 已经下载的数据块
@blocksize: 数据块的大小
@totalsize: 远程文件的大小
'''
def Schedule(blocknum, blocksize, totalsize):
speed = (blocknum * blocksize) / (time.time() - start_time)
# speed_str = " Speed: %.2f" % speed
speed_str = " Speed: %s" % format_size(speed)
recv_size = blocknum * blocksize
# 设置下载进度条
f = sys.stdout
pervent = recv_size / totalsize
percent_str = "%.2f%%" % (pervent * 100)
n = round(pervent * 50)
s = ('#' * n).ljust(50, '-')
f.write(percent_str.ljust(8, ' ') + '[' + s + ']' + speed_str)
f.flush()
# time.sleep(0.1)
f.write('\r')
# 字节bytes转化K\M\G
def format_size(bytes):
try:
bytes = float(bytes)
kb = bytes / 1024
except:
print("传入的字节格式不对")
return "Error"
if kb >= 1024:
M = kb / 1024
if M >= 1024:
G = M / 1024
return "%.3fG" % (G)
else:
return "%.3fM" % (M)
else:
return "%.3fK" % (kb)
if __name__ == '__main__':
# print(format_size(1222222222))
start_time = time.time()
print(downloadUrl)
print(downloadName)
def validateTitle(downloadName):
rstr = r"[\/\\\:\*\?\"\<\>\|]" # '/ \ : * ? " < > |'
new_downloadName = re.sub(rstr, "_", downloadName) # 替换为下划线
new_downloadName = new_downloadName.replace("'","_")
new_downloadName = new_downloadName.replace(" ","_")
new_downloadName = new_downloadName.replace("]","_")
new_downloadName = new_downloadName.replace("[","_") return new_downloadName
urllib.request.urlretrieve(downloadUrl,validateTitle(downloadName),Schedule)
网友评论