【问题标题】:How can I pass the for loop variable to c in puppeteer如何在 puppeteer 中将 for 循环变量传递给 c
【发布时间】:2019-01-08 10:05:25
【问题描述】:

我想将 for 循环变量传递给 puppeteer 中的 page.evaluate,以获取画廊的所有量具。但它不起作用。它总是报告UnhandledPromiseRejectionWarning: Error: Evaluation failed

以下是我的代码示例:

const puppeteer = require('puppeteer-core');

(async () => {
    const browser = await puppeteer.launch({executablePath:'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'});
    const page = await browser.newPage();
    await page.goto('D:\\Code Workplace\\Javascripts\\TurnPage\\index.html', {waitUntil: 'networkidle2'});
    for (let index = 0; index < 4; index++) {
        await page.evaluateHandle((index) => {
            $('.flipbook').turn('page', index);
        }, index);
    }
    await sleep(300);
    await page.emulateMedia('print');
    await page.pdf({path: 'hn.pdf', format: 'A4', printBackground: true});
    await browser.close();
})();

所以我需要帮助将循环变量传递给变量。以前有人遇到过这个问题吗?感谢您的热心帮助。

【问题讨论】:

    标签: puppeteer evaluate


    【解决方案1】:

    编辑:

    我测试了它在 puppeteer 中抛出 2 个错误的页面:

    1. 无需等待 jQuery 和 turn.js 插件加载

      评估失败:ReferenceError: $ 未定义

    2. index 必须从 1 开始,而不是 0

      错误:评估失败:TurnJsError

    固定代码:

    await page.waitForFunction('typeof(jQuery) == "function" && typeof($().turn) == "function"', {
      timeout: 5000
    });
    
    for (let index = 1; index < 8; index++) {
      await page.evaluateHandle((index) => {
        $('.flipbook').turn('page', index);
      }, index);
    
      //await sleep(2000); // for debugging
    }
    

    【讨论】:

    • 我认为重点不在于是否加载了turn.js。因为它是在page.goto之后执行的,当我使用await page.evaluateHandle((index) =&gt; {$('.flipbook').turn('page', 2)});时,它起作用了。
    • 我多次尝试运行此操作,它也有效。为什么你认为它运行几次就会失败?如果单个操作有效,是否意味着该功能已经加载?
    • 在我的环境中有时它会起作用,因为 jQuery 加载到缓存中,您是否尝试过我的答案中的代码?
    • 是的,我已经尝试过您的代码。但这似乎陷入了循环,无法完成。我也尝试将page.setCacheEnabled设置为false,单动作依然有效。
    • 当然,你可以用这个link来运行一些测试。
    猜你喜欢
    • 1970-01-01
    • 2017-04-01
    • 2021-06-21
    • 2014-10-05
    • 1970-01-01
    • 2021-05-31
    • 2013-10-25
    • 1970-01-01
    • 2019-11-29
    相关资源
    最近更新 更多