Skip to content

页面元素截图脚本

js
function loadHtml2Canvas() {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = "https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js";
        script.onload = () => resolve(window.html2canvas);
        script.onerror = reject;
        document.body.appendChild(script);
    });
}

// 使用示例
loadHtml2Canvas().then(html2canvas => {
    console.log('库加载完成,可以调用截图');
});


async function doScreenshot() {
    await new Promise(resolve => setTimeout(resolve, 3000));
    const dom = document.getElementsByClassName("question-item")[0];
    const name = document.querySelector('.question-number').textContent.slice(0, -1);
    // 生成canvas
    const canvas = await html2canvas(dom, {
        useCORS: true, //处理跨域图片
        scale: window.devicePixelRatio //高清
    });
    //转图片url
    const imgUrl = canvas.toDataURL("image/png");
    //创建下载链接自动下载图片
    const a = document.createElement('a');
    a.href = imgUrl;
    count++;
    a.download = name + ".png";
    a.click();
}


document.addEventListener('DOMContentLoaded', function () {
    const btnList = document.querySelectorAll('.question-button');
    btnList.forEach(btn => {
        doScreenshot();
    });
});


//事件委托,支持动态生成的按钮
document.body.addEventListener('click', function (e) {
    if (e.target.matches('.question-button')) {
        doScreenshot();
    }
});


/**
 * 逐个模拟点击 .question-button 按钮,每个按钮之间间隔 10‑20秒随机时长
 */
async function autoClickQuestionButtons() {
    const btnList = document.querySelectorAll('.question-button');

    for (const btn of btnList) {
        // 生成10000 ~ 20000 毫秒随机延时(10‑20秒)
        const randomDelay = Math.floor(Math.random() * (20000 - 10000 + 1)) + 10000;
        console.log(`等待 ${ (randomDelay / 1000).toFixed(1) }s 后点击按钮`);

        // 等待随机间隔
        await new Promise(resolve => setTimeout(resolve, randomDelay));

        // 触发原生click点击事件
        btn.click();
    }
    console.log('全部按钮自动点击完成');
}