Home > OS >  Puppeteer: line of code being executed before others
Puppeteer: line of code being executed before others

Time:10-12

I have this code:

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto("https://www.sisal.it/scommesse-matchpoint/quote/calcio/serie-a");

    const [button1] = await 
       page.$x('//div[@class="marketBar_changeMarketLabel__l0vzl"]/p');
    button1.click();

    const [button2] = await page.$x('//div[@class="listItem_container__2IdVR white 
       marketList_listItemHeight__1aiAJ marketList_bgColorGrey__VdrVK"]/p[text()="1X2 
       ESITO FINALE"]');
    button2.click();
})();

The proble is that after clicking button1 the page change and puppeteer executes immediately the following line of code, instead I want it to wait for the new page to be loaded becuase otherwise It will throw an error since It can't find button2.

I found this solution on stackoverflow:

const puppeteer = require("puppeteer");

function delay(time) {
    return new Promise(function (resolve) { 
        setTimeout(resolve, time);
    });
}

(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto("https://www.sisal.it/scommesse-matchpoint/quote/calcio/serie-a");

    const [button1] = await 
        page.$x('//div[@class="marketBar_changeMarketLabel__l0vzl"]/p');
    button1.click();

    await delay(4000);

    const [button2] = await page.$x('//div[@class="listItem_container__2IdVR white 
       marketList_listItemHeight__1aiAJ 
       marketList_bgColorGrey__VdrVK"]/p[text()="1X2 
       ESITO FINALE"]');
    button2.click();
})();

But of course this in't the best solution.

CodePudding user response:

I think you have to modify a bit in your code:

await button1.click();
await page.waitForNavigation({waitUntil: 'networkidle2'});

For reference, see the documentation.

CodePudding user response:

I found a solution, here's the code:

const puppeteer = require("puppeteer");

(async () => {
    const browser = await puppeteer.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto("https://www.sisal.it/scommesse 
        matchpoint/quote/calcio/serie-a");

    await page.waitForXPath('//div[@class="marketBar_changeMarketLabel__l0vzl"]/p');
    const [button1] = await page.$x('//div[@class="marketBar_changeMarketLabel__l0vzl"]/p');
    await button1.click();

    await page.waitForXPath('//div[@class="listItem_container__2IdVR white marketList_listItemHeight__1aiAJ marketList_bgColorGrey__VdrVK"]/p[text()="1X2 ESITO FINALE"]');
    const [button2] = await page.$x('//div[@class="listItem_container__2IdVR white marketList_listItemHeight__1aiAJ marketList_bgColorGrey__VdrVK"]/p[text()="1X2 ESITO FINALE"]');
    button2.click();
})();
  • Related