Puppeteer浏览器和页面立即关闭,page.evaluate在bloc 2上不起作用

问题描述 投票:0回答:1

我有这个脚本,一切正常,直到第2块开始我不明白为什么它不执行第2块中的工作,我应该在“ page.on request”中返回一个值,但是它不是直接离开的情况,您对这个问题有想法吗?

节点向我返回没有错误

谢谢

async function main() {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    await page.setViewport({width: 1200, height: 720})
    await page.goto('https://site.local', { waitUntil: 'networkidle0' }); // wait until page load
    await page.type("input[name='UserName']", "myusername");
    await page.type("input[name='Password']", "mypassworduser");
    // click and wait for navigation
    await Promise.all([
            page.click("body > main > button"),
            page.waitForNavigation({ waitUntil: 'networkidle0' }),
    ]);

    await page.goto(urlformation);

    await page.setRequestInterception(true);

    await page.on('request', (request) => { 
      if (request.resourceType() === 'media') {
        var CurrentRequest  = request.url();
        console.log(CurrentRequest);
        fs.appendFileSync(fichiernurlaudio, request.url()+"\r\n"); 
      }
      request.continue();

    }); 
//START BLOC 1 ------------------IT WORK    
    const Titresaudios = await page.evaluate(() => {
        let names = document.querySelectorAll(
            "td.cursor.audio"
        );
        let arr = Array.prototype.slice.call(names);
        let text_arr = [];
        for (let i = 0; i < arr.length; i += 1) {
            text_arr.push($vartraited+"\r\n");
        }
        return text_arr;
    })
    fs.appendFileSync(fichiernomaudio, Titresaudios);
//END BLOCK 1------------------IT WORK- i got data in my file   

//START BLOCK 2-------seems to ignore-----------NOT WORKING
    await page.evaluate(()=>{

        let elements = document.querySelectorAll("td.cursor.audio");    

        elements.forEach((element, index) => {
                setTimeout(() => {
                    element.click();
                }, index * 1000);  
        })

    })
//END BLOCK 2---------seems to ignore---------NO WORKING 

//i should see some console.log in page.on('request' (request) => { but instant close after works of bloc 1


    await page.close();
    await browser.close();


}

main();
javascript browser puppeteer evaluate
1个回答
0
投票

我不知道,您到底想达到什么目的,但是可以像这样重写该块:

// ...
const els = await page.$$( 'td.cursor.audio' );
for( const el of els ) {

  // basically your timeout, but from outside the browser
  await page.waitFor( 1000 );

  // perform the action
  await el.click();

}
// ...

根据我的经验,通常建议您在NodeJS中而不是在浏览器中执行尽可能多的操作。通常也可以简化调试。

© www.soinside.com 2019 - 2024. All rights reserved.