How to handle iframes in Puppeteer?

To handle iframes in Puppeteer, you have to understand that an iframe is essentially a separate HTML document embedded inside your main document. This means you need to get a reference to the iframe before you can interact with its content.

Here's how you can do it:

Puppeteer JavaScript code:

First of all, you need to wait for the iframe to load. You can do this by waiting for a particular element inside the iframe to be visible. This element will depend on your specific use case.

Once the iframe is loaded, you can get a reference to it like this:

const elementHandle = await page.$('iframe.selector'); // replace 'iframe.selector' with your iframe selector
const frame = await elementHandle.contentFrame();

Now that you have a reference to the iframe, you can interact with it like you would with a normal page:

await frame.click('button'); // clicks a button inside the iframe

Complete Example

Here's a complete example that navigates to a page, waits for an iframe to load, and then clicks a button inside the iframe:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('http://example.com/');

  const elementHandle = await page.$('#iframeId'); // replace '#iframeId' with your iframe selector
  const frame = await elementHandle.contentFrame();

  await frame.waitForSelector('#buttonId'); // replace '#buttonId' with the selector of a button inside the iframe
  await frame.click('#buttonId'); // clicks the button

  await browser.close();
})();

Remember to replace '#iframeId' and '#buttonId' with your actual selectors.

Please note that if the iframe or the elements inside the iframe don't load instantly, you might need to add some waitForSelector, waitForNavigation, or waitFor calls to ensure that the iframe is loaded before you try to interact with it.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon