I am very new to puppeteer. I have a puppeteer script (node v20.15.0) and I’m trying to write/print to the command line from inside a page.evaluate that’s inside an async function. I was following this example:
https://stackoverflow.com/a/61336937/1827764
If I run that code, it works perfectly. I can even modify it to pass a variable like this:
await page.exposeFunction("myFunc", (value) => console.log(value));
await page.evaluate(async () => {
await myFunc('test');
return true;
});
However, I have something like this:
const puppeteer = require('puppeteer');
const fs = require('fs'); //filesystem functions
const path = require('path'); //path-related functions
const https = require('https')
process.on('uncaughtException', function (exception) {
console.log(exception);
});
(async () => {
var browser;
var puppeteer_options = {
headless: true,
ignoreHTTPSErrors: true,
args: ['--no-sandbox', '--disable-setuid-sandbox', '--single-process', '--no-zygote', '--disable-dev-shm-usage', '--shm-size=4gb', ],
defaultViewport: {width: 1920, height: 1080},
protocolTimeout: 1000000, //https://www.puppeteersharp.com/api/PuppeteerSharp.LaunchOptions.html
}
browser = await puppeteer.launch(puppeteer_options);
var page = await browser.newPage();
await page.exposeFunction("logInNodeJs", (value) => console.log(value));
var gp_args = {}
gp_args['x_data'] = {}
if(gp_args['x_data'])
{
var x = await get_x({x_data: gp_args['x_data'], gp_args:gp_args})
}
async function get_x(options)
{
var url = '<url>'
await page.setDefaultNavigationTimeout(0)
await page.goto(url, {waitUntil: 'networkidle2'});
gp_args['waitforselector'] = "div[class='paging']"
gp_args['waitforselector_timeout'] = 30000
try
{
await page.waitForSelector(gp_args['waitforselector'], {visible: true, timeout: gp_args['waitforselector_timeout'] })
}
catch(err)
{
console.log(err)
return
}
var el = await page.evaluate(async () => {
await logInNodeJs('test 1')
var el = document.querySelector("div[class='paging']")
pages = el.querySelectorAll('a')
return pages.length - 1
})
console.log(el)
}
})()
In this example, when the “await logInNodeJs(‘test 1’)” runs, the only output I get is:
[
just a left bracket. I don’t know why it isn’t printing out ‘test 1’, and I don’t know where the “[” is coming from.