How to handle popover windows with Puppeteer

Viewed 191

I'm writing a script to purchase items on Amazon.

const puppeteer = require('puppeteer');

// Insert personal credentials
const email = '';
const password = '';

function press_enter(page) {
    return Promise.all([
        page.waitForNavigation({waitUntil:'networkidle2'}),
        page.keyboard.press(String.fromCharCode(13))
      ]);
}

function click_wait(page, selector) {
    return Promise.all([
        page.waitForNavigation({waitUntil:'networkidle2'}),
        page.click(selector)
      ]);
}

(async () => {
  const browser = await puppeteer.launch({headless:false, defaultViewport:null, args: ['--start-maximized']});
  const page = (await browser.pages())[0];
  await page.goto('https://www.amazon.it/');
  await click_wait(page, "a[data-nav-role='signin']");
  await page.keyboard.type(email);
  await press_enter(page);
  await page.keyboard.type(password);
  await press_enter(page);

  // Search for the "signout" button as login proof
  if(await page.$('#nav-item-signout') !== null) console.log('Login done!');
  else return console.log('Something went wrong during login');

  // Navigate to the product page
  await page.goto('https://www.amazon.it/dp/B07RL2VWXQ');

  // Click "buy now" (choose either Option A or Option B)

    // Option A: Here the code get stuck since the page isn't refreshing and page.waitForNavigation() will reach its timeout
    // await click_wait(page, "#buy-now-button");

    // Option B: Waiting time manually set to 5 seconds (it should be more than enough for popover to fully load)
    await Promise.all([page.waitForTimeout(5000), page.click('#buy-now-button')]);

  // Conclude the purchase
  await click_wait(page, '#turbo-checkout-pyo-button');
})();

So far I can login to Amazon, navigate to a product page and click the Buy Now button.
Then, if delivery address and payment option are all set up, (depending on Amazon domain) it may show up a pop-over box to conclude the purchase.
I wasn't able to replicate the popover response on .com and .co.uk, it seems that these domains will redirect you on a totally new page.

Amazon.it "buy now" popover window

When I explore the page with Chrome Developer Tools I actually see the new chunk of the page being loaded (<!DOCTYPE html>) but I don't know where the representation of this element resides in Puppeteer.

If I use click_wait() to click Buy Now, the script gets stuck (it only returns after the default timeout of page.waitForNavigation()) so it's not considered a refreshing of the page. But even if I just wait a few seconds after clicking Buy Now and then attempt to click input[id='turbo-checkout-pyo-button'] (the orange button "Ordina") Puppeteer throws an error cause it can't find the element, despite it being clearly loaded.

0 Answers
Related