page.$$eval() not working as expected (Puppeteer)

In a page, there are bunch of elements which a specific class.

The below code doesn’t print the no. of elements:

await page.$$eval(scoreSelector, (ele) => {
    console.log(ele.length);

Whereas, this works as expected:

curLiveScoreElements = await page.$$(scoreSelector)

Please clarify.

5 thoughts on “page.$$eval() not working as expected (Puppeteer)”

  1. When using page.$$eval(), you can obtain the length of the elements in question with:

    const curLiveScoreElements = await page.$$eval( scoreSelector, ele => ele.length );
    
    console.log( curLiveScoreElements );
    

    You can also use page.$$() to obtain an ElementHandle array, like you mentioned, in which you can log the length of the result:

    const curLiveScoreElements = await page.$$( scoreSelector );
    
    console.log( curLiveScoreElements.length );
    

    Alternatively, you can listen for the 'console' event to happen within the page, and display the results:

    page.on( 'console', msg => {
        for ( let i = 0; i < msg.args().length; i++ ) {
            console.log( `${i}: ${msg.args()[i]}` );
        }
    });
    
    const curLiveScoreElements = await page.$$( scoreSelector );
    
    await page.evaluate( ele => { console.log( ele.length ); }, curLiveScoreElements );
    
    Reply
  2. As I understand you expect to see some console output. And you do not see it in command line interface (CLI), so you decided that code is not working.

    Just pay attention that code invoked in your handler (second argument of $$eval) is executed within browser. So you will found your console output in browser, not in CLI.
    To see browser’s console output in CLI you have to intercept browser console calls.
    You could get an example on https://stackoverflow.com/a/46245945/3452033

    Reply

Leave a Comment