思路:
1.浏览器窗口调到只露出弹框“下一节的按钮”,然后把这个单页面,置顶到电脑最顶层
2.使用openvc进行识别,实现自动播放
3.js代码开启16倍。

import numpy as np
import cv2
import time
import random
import threading

import pyautogui
import win32gui
import win32con
import cv2
import numpy as np
# ================== 基础配置 ==================

# Chrome 窗口标题中包含的关键字(一般“慕课网”就够)
CHROME_TITLE_KEYWORD = "慕课"

# 下一节按钮截图路径
NEXT_BTN_IMAGE = "next.png"

# 识别精度(0.8~0.9 推荐)
IMAGE_CONFIDENCE = 0.85

# 检测间隔(秒)
CHECK_INTERVAL = 3

# 点击后等待时间(模拟人)
AFTER_CLICK_WAIT = (5, 8)

# 鼠标移动时间
MOUSE_MOVE_TIME = (0.3, 0.7)

# =================================================

pyautogui.FAILSAFE = True
pyautogui.PAUSE = 0.1


# ================== 窗口置顶 ==================

def keep_chrome_topmost():
    """
    定期将 Chrome 窗口置顶,防止浏览器进入后台冻结
    """
    while True:
        try:
            def enum_handler(hwnd, _):
                title = win32gui.GetWindowText(hwnd)
                if CHROME_TITLE_KEYWORD in title:
                    win32gui.SetWindowPos(
                        hwnd,
                        win32con.HWND_TOPMOST,
                        0, 0, 0, 0,
                        win32con.SWP_NOMOVE | win32con.SWP_NOSIZE
                    )

            win32gui.EnumWindows(enum_handler, None)
        except Exception as e:
            print("[WARN] 置顶失败:", e)

        time.sleep(10)


# ================== 拟人点击 ==================

def human_move_and_click(x, y):
    """
    像人一样移动鼠标并点击
    """
    cur_x, cur_y = pyautogui.position()

    duration = random.uniform(*MOUSE_MOVE_TIME)
    target_x = x + random.randint(-3, 3)
    target_y = y + random.randint(-3, 3)

    pyautogui.moveTo(target_x, target_y, duration=duration)
    time.sleep(random.uniform(0.2, 0.5))
    pyautogui.click()


# ================== 核心逻辑 ==================


def try_click_next():
    """
    使用 OpenCV 进行多尺度模板匹配,提升识别稳定性
    """
    # 读取屏幕截图(全屏)
    screenshot = pyautogui.screenshot()
    screen = cv2.cvtColor(np.array(screenshot), cv2.COLOR_RGB2BGR)

    # 读取模板(下一节按钮)
    template = cv2.imread(NEXT_BTN_IMAGE, cv2.IMREAD_COLOR)
    if template is None:
        print(f"[ERROR] 无法加载模板图片: {NEXT_BTN_IMAGE}")
        return False

    h, w = template.shape[:2]

    # 转为灰度图(提升速度和鲁棒性)
    screen_gray = cv2.cvtColor(screen, cv2.COLOR_BGR2GRAY)
    template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)

    best_match = None
    best_val = -1
    best_loc = None

    # 尝试多个缩放比例(应对浏览器缩放)
    scales = [0.9, 0.95, 1.0, 1.05, 1.1]
    for scale in scales:
        tw, th = int(w * scale), int(h * scale)
        if tw == 0 or th == 0:
            continue
        resized_template = cv2.resize(template_gray, (tw, th))

        # 模板匹配
        res = cv2.matchTemplate(
            screen_gray, resized_template, cv2.TM_CCOEFF_NORMED)
        _, max_val, _, max_loc = cv2.minMaxLoc(res)

        if max_val > best_val:
            best_val = max_val
            best_loc = max_loc
            best_match = (tw, th)

    if best_val >= IMAGE_CONFIDENCE:
        x = best_loc[0] + best_match[0] // 2
        y = best_loc[1] + best_match[1] // 2
        print(f"[INFO] 匹配成功!置信度: {best_val:.3f},点击位置: ({x}, {y})")
        human_move_and_click(x, y)
        return True
    else:
        # 可选:调试时保存截图便于分析
        # cv2.imwrite("debug_screen.png", screen)
        # print(f"[DEBUG] 最佳匹配置信度: {best_val:.3f}")
        return False


def main_loop():
    print("======================================")
    print(" 慕课网 自动下一节(最稳版) 已启动")
    print(" 按 Ctrl + C 结束程序")
    print("======================================")

    while True:
        try:
            clicked = try_click_next()

            if clicked:
                wait_time = random.uniform(*AFTER_CLICK_WAIT)
                print(f"[INFO] 已点击,等待 {wait_time:.1f} 秒")
                time.sleep(wait_time)
            else:
                time.sleep(CHECK_INTERVAL)

        except KeyboardInterrupt:
            print("\n[EXIT] 用户中断,程序退出")
            break
        except Exception as e:
            print("[ERROR] 运行异常:", e)
            time.sleep(5)


# ================== 程序入口 ==================

if __name__ == "__main__":
    # 后台线程:保持窗口置顶
    t = threading.Thread(target=keep_chrome_topmost, daemon=True)
    t.start()

    # 主循环
    main_loop()

(function () {
    function enforcePlaybackSpeed() {
        const video = document.querySelector('video');
        if (video && video.playbackRate !== 16) {
            video.playbackRate = 16;
            console.log('[倍速守护] 已设置播放速度为 16 倍');
        }
    }

    // 立即执行一次
    enforcePlaybackSpeed();

    // 每 5 秒检查并强制设置一次
    const intervalId = setInterval(enforcePlaybackSpeed, 5000);

    // 可选:将 intervalId 挂到 window 上,方便手动清除
    window.__speedGuardInterval = intervalId;

    console.log('[倍速守护] 已启动,每 5 秒确保视频为 16 倍速');
})();
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐