Puppeteer - How to fill form that is inside an iframe?

早过忘川 提交于 2019-12-05 14:37:45

问题


I have to fill out a form that is inside an iframe, here the sample page. I cannot access by simply using page.focus() and page.type(). I tried to get the form iframe by using const formFrame = page.mainFrame().childFrames()[0], which works but I cannot really interact with the form iframe.


回答1:


Instead of figuring out how to get inside the iFrame and type, I would simplify the problem by navigating to the IFrame URL directly

https://warranty.goodmanmfg.com/registration/NewRegistration/NewRegistration.aspx?Sender=Goodman

Make your script directly go to the above URL and try automating, it should work

Edit-1: Using frames

Since the simple approach didn't work for you, we do it with the frames itself

Below is a simple script which should help you get started

const puppeteer = require('puppeteer');
(async () => {
  const browser = await puppeteer.launch({headless: false});
  const page = await browser.newPage();
  await page.goto('http://www.goodmanmfg.com/product-registration', {timeout: 80000});
    var frames = await page.frames();
    var myframe = frames.find(
        f =>
            f.url().indexOf("NewRegistration") > 0);
    const serialNumber = await myframe.$("#MainContent_SerNumText");
    await serialNumber.type("12345");

    await page.screenshot({path: 'example.png'});

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

The output is




回答2:


I figured it out myself. Here's the code.

console.log('waiting for iframe with form to be ready.');
await page.waitForSelector('iframe');
console.log('iframe is ready. Loading iframe content');

const elementHandle = await page.$(
    'iframe[src="https://example.com"]',
);
const frame = await elementHandle.contentFrame();

console.log('filling form in iframe');
await frame.type('#Name', 'Bob', { delay: 100 });



回答3:


Though you have figured out but I think I have better solution. Hope it helps.

async doFillForm() {
    return await this.page.evaluate(() => {
       let iframe = document.getElementById('frame_id_where_form_is _present');
       let doc = iframe.contentDocument;
       doc.querySelector('#username').value='Bob';
       doc.querySelector('#password').value='pass123';
    });
}


来源:https://stackoverflow.com/questions/46529201/puppeteer-how-to-fill-form-that-is-inside-an-iframe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!