| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 
 | import os;import re;
 import time
 from datetime import datetime;
 from urllib.parse import urlparse, urlunparse, parse_qs, urlencode
 
 # 获取某个目录下的所有的js和html文件,并读取内容
 def fileList(directory):
 filesInfo = []
 for root, dirs, files in os.walk(directory):
 for file in files:
 # if file.endswith('.html') or file.endswith('.js'):
 if file.endswith('.html') :
 filePath = os.path.join(root, file)
 filesInfo.append({'name': file, 'path': filePath})
 return filesInfo
 
 # 替换时间戳
 def replaceTimestamp(filePath):
 print(filePath)
 replaceSuffix(filePath,".js");
 # replaceSuffix(filePath,".css");
 
 # 替换后缀
 def replaceSuffix(filePath, suffix):
 with open(filePath, 'r', encoding='utf-8') as file:
 fileContent = file.read();
 content = add_timestamp_to_assets(fileContent);
 with open(filePath, 'w+', encoding='utf-8') as file:
 file.write(content);
 
 def add_or_update_timestamp(url):
 # 解析 URL
 parsed_url = urlparse(url)
 
 # 解析查询参数
 query_params = parse_qs(parsed_url.query)
 
 # 检查是否已经有时间戳参数
 if 't' in query_params:
 # 替换旧的时间戳
 query_params['v'] = [loadTimestamp()]
 else:
 # 添加新的时间戳参数
 query_params['v'] = [loadTimestamp()]
 
 # 重新编码查询参数
 new_query = urlencode(query_params, doseq=True)
 
 # 构造新的 URL
 new_parsed_url = parsed_url._replace(query=new_query)
 new_url = urlunparse(new_parsed_url)
 
 return new_url
 
 def add_timestamp_to_assets(html_content):
 
 # 定义正则表达式模式来匹配 CSS 和 JS 文件的引用
 css_js_pattern = re.compile(r'(<(link|script)[^>]*\b(?:href|src)=["\'])([^"\']+)(["\'][^>]*>)', re.IGNORECASE)
 
 # 使用 sub() 方法替换匹配到的内容,增加或更新时间戳
 def update_asset_url(match):
 prefix = match.group(1)  # <link ...src=" 或 <script ...src="
 url = match.group(3)     # CSS 或 JS 文件的 URL
 suffix = match.group(4)  # " ...> 或 ' ...>
 
 # 更新 URL 中的时间戳
 updated_url = add_or_update_timestamp(url)
 
 return prefix + updated_url + suffix
 
 # 执行替换
 updated_html_content = css_js_pattern.sub(update_asset_url, html_content)
 
 return updated_html_content
 
 def loadTimestamp():
 # 获取当前时间戳
 timestamp = time.time()
 # 将时间戳转换为 datetime 对象
 dt_object = datetime.fromtimestamp(timestamp)
 # 将 datetime 对象格式化为字符串
 formatted_time = dt_object.strftime("%Y%m%d%H%M%S")
 return formatted_time;
 # 示例使用
 dirPath = 'C:/Users/Administrator/Desktop/test'
 dirPath = './';
 files = fileList(dirPath)
 for info in files:
 replaceTimestamp(info['path']);
 # print(f"File Name: {info['name']}, Path: {info['path']}")
 
 |