【问题标题】:How to loop through variables in input box and save the HTML using Puppeteer如何循环输入框中的变量并使用 Puppeteer 保存 HTML
【发布时间】:2021-06-02 21:19:58
【问题描述】:

如果直接使用,我可以在使用 puppeteer 做某事后保存文件。现在,我想对变量 1 到 2000 执行此操作。为此,我什至创建了一个变量 i,但它似乎仍然不起作用。请参考下面的代码(第 6、14 和 22 行的 cmets):

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  i = '1163'; //Created this variable to loop through numbers from 1 to 2000
  await page.setRequestInterception(true);
  page.on('request', (request) => {
    if (request.resourceType() === 'image') request.abort();
    else request.continue();
  });
  await page.goto('http://example.com/Print_New.aspx');
  console.log(i);
  await page.$eval('#TextBox1', el => el.value = i); //Unable to use the variable
  const [response] = await Promise.all([
    page.waitForNavigation(),
    page.click('input[type="submit"]'),
  ]);
  const html = await page.content();
  const fs = require('fs');
  fs.writeFile(`./out${i}.html`, html, function(err) { //Able to use the variable inside this. File is getting saved.
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
}); 
  await browser.close();
})();

【问题讨论】:

  • 这是什么页面?

标签: javascript node.js async-await puppeteer


【解决方案1】:

page.$eval()中,函数参数是在浏览器上下文中执行的,所以需要从Node.js上下文中传递变量作为参数:

await page.$eval('#TextBox1', (el, num) => el.value = num, i);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-03
    相关资源
    最近更新 更多