import os import re import time import threading from selenium import webdriver from selenium.webdriver.edge.service import Service import keyboard # 监听键盘 def get_number_from_filename(filename): match = re.match(r'(\d+)\.html$', filename) if match: return int(match.group(1)) return None def build_file_url(folder, num): filename = f"{num}.html" path = os.path.join(folder, filename) return "file:///" + os.path.abspath(path).replace("\\", "/") def main(): # 选择HTML文件路径(这里直接写死,或者你用tkinter选择) from tkinter import Tk, filedialog root = Tk() root.withdraw() file_path = filedialog.askopenfilename( title="选择数字命名的HTML文件", filetypes=[("HTML files", "*.html")]) if not file_path: print("未选择文件,程序退出") return folder = os.path.dirname(file_path) filename = os.path.basename(file_path) current_num = get_number_from_filename(filename) if current_num is None: print("文件名格式不正确,必须是数字.html") return # Edge driver路径 edge_driver_path = r"C:\Users\dxkcw\Desktop\xiaoshuo\msedgedriver.exe" service = Service(edge_driver_path) options = webdriver.EdgeOptions() options.use_chromium = True driver = webdriver.Edge(service=service, options=options) # 打开初始页面 url = build_file_url(folder, current_num) driver.get(url) print(f"打开页面:{url}") def on_press_key(): nonlocal current_num while True: event = keyboard.read_event(suppress=False) # 监听键盘事件,不阻止系统响应 if event.event_type == keyboard.KEY_DOWN: if event.name == "left": if current_num > 1: next_num = current_num - 1 next_path = os.path.join(folder, f"{next_num}.html") if os.path.exists(next_path): current_num = next_num next_url = build_file_url(folder, current_num) driver.get(next_url) print(f"切换到 {current_num}.html") elif event.name == "right": next_num = current_num + 1 next_path = os.path.join(folder, f"{next_num}.html") if os.path.exists(next_path): current_num = next_num next_url = build_file_url(folder, current_num) driver.get(next_url) print(f"切换到 {current_num}.html") elif event.name == "esc": print("检测到ESC,退出程序") driver.quit() os._exit(0) # 监听键盘线程 listener_thread = threading.Thread(target=on_press_key, daemon=True) listener_thread.start() # 主线程阻塞,保持浏览器打开 try: while True: time.sleep(1) except KeyboardInterrupt: driver.quit() print("程序退出") if __name__ == "__main__": main()