Puppeteer - 如何填写iframe内的表单?

时间:2017-10-02 15:56:45

标签: puppeteer

我必须填写iframe内的表单,此处为sample page。仅使用page.focus()page.type()无法访问。我尝试使用const formFrame = page.mainFrame().childFrames()[0]来获取表单iframe,但是我无法与表单iframe进行交互。

4 个答案:

答案 0 :(得分:15)

如果您无法选择/查找iFrame,请阅读以下内容:

我在寻找条纹元素时遇到问题。 原因如下:

您无法使用JavaScript访问其他来源的内容,如果可以的话,这将是一个巨大的安全漏洞。对于同源策略,浏览器会阻止脚本尝试访问具有不同来源的框架。 See more detailed answer here

因此,当我尝试使用伪造者的方法:Page.frames()Page.mainFrame(). ElementHandle.contentFrame()时,我没有向我返回任何iframe。问题在于它正在默默发生,我无法弄清为什么找不到任何东西。

将这些参数添加到启动选项可以解决此问题: '--disable-web-security', '--disable-features=IsolateOrigins,site-per-process'

答案 1 :(得分:12)

我没有弄清楚如何进入iFrame并输入内容,而是直接导航到IFrame网址来简化问题

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

让您的脚本直接转到上面的URL并尝试自动化,它应该可以正常工作

编辑-1:使用框架

由于简单方法对您不起作用,我们使用框架本身

下面是一个简单的脚本,可以帮助您入门

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();
})();

输出

Type serial

答案 2 :(得分:1)

我自己弄清楚了。这是代码。

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 :(得分:0)

尽管您已经找到答案,但是我认为我有更好的解决方案。希望对您有所帮助。

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';
    });
}
相关问题