I am able to save file after doing something using puppeteer for one case if used directly. Now, I want to do this for variable 1 to 2000. For this, I even created a variable i
but still it doesn't appear to work. Refer the code (comments on line 6, 14 and 22) below:
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();
})();
In page.$eval()
, the function argument is executed in the browser context, so you need to transfer variables from the Node.js context as arguments:
await page.$eval('#TextBox1', (el, num) => el.value = num, i);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.