简体   繁体   中英

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.

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 );

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM