0

Messing around with puppeteer, and not seeing this question answered anywhere, although it has been asked a few times:

Expected result: 1. Click on tag via its class name 2. wait for new page (linked in tag) to finish loading 3. take a screenshot of new page to demonstrate this process has been successful

Here's my code:

const puppeteer = require('puppeteer');
const browser = await puppeteer.launch()
const page = await browser.newPage()

await page.setViewport({
  width: 800,
  height: 600
})

await page.goto('https://www.example.com/')

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

await page.screenshot({
  path: 'mouse_click.png'
})
await browser.close()

I expected the screenshot to contain the page navigated to via the clicked tag. Instead it times out. If I remove the waitForNavigation, it just screenshots the initial page loaded.

Can anyone tell me where I have gone wrong here?

Thanks!

Khepf
  • 352
  • 1
  • 4
  • 24
  • 1
    While the example isn't really reproducible, make sure to use the `Promise.all` pattern when clicking things that trigger navigation as described [in this answer](https://stackoverflow.com/a/54781467/6243352) and [this GH issue](https://github.com/puppeteer/puppeteer/issues/1412#issuecomment-345357063). – ggorlen Feb 06 '21 at 15:45

2 Answers2

1

Try waiting for a selector on the new page: await page.waitForSelector('.someThingOnThisPage'); in place of waitForNavigation

Alan Friedman
  • 1,582
  • 9
  • 7
  • This still times out waiting for any selector I assign to it on the new page. Maybe I'm not understanding exactly how the headless browser works, even independently of puppeteer. I'm basically just trying to automate the process of clicking on a link tag and confirming the new page has loaded by taking a screenshot. Is this behavior possible using puppeteer/headless browser? – Khepf Jan 17 '19 at 14:15
1

As @ggorlen pointed out in the comment below, you should be using the Promise.all pattern. Here's your code with the proper changes:

const puppeteer = require('puppeteer');

const browser = await puppeteer.launch()
const page = await browser.newPage()

await page.setViewport({
  width: 800,
  height: 600
})

await page.goto('https://www.example.com/')

const linkSelector = '.targeted_class_with_a_tag';
await page.waitForSelector(linkSelector);
await Promise.all([
    page.click(linkSelector),
    page.waitForNavigation({ waitUntil: 'networkidle2' })
]);

await page.screenshot({
  path: 'mouse_click.png'
})
await browser.close()
ifthenelse
  • 647
  • 1
  • 11
  • 21