如何在Puppeteer中的iframe元素中选择元素 [英] How to select elements within an iframe element in Puppeteer

查看:2534
本文介绍了如何在Puppeteer中的iframe元素中选择元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于ESPN不提供API,所以我试图使用Puppeteer来获取有关我的梦幻足球联赛的数据.但是,由于登录表单与iframe元素嵌套在一起,因此我很难尝试使用puppeteer登录.

Since ESPN does not provide an API, I am trying to use Puppeteer to scrape data about my fantasy football league. However, I am having a hard time trying to login using puppeteer due to the login form being nested with an iframe element.

我已经转到 http://www.espn.com/login 并选择了iframe.我似乎无法通过操作选择iframe中除主要部分以外的任何元素

I have gone to http://www.espn.com/login and selected the iframe. I can't seem to select any of the elements within the iframe except for the main section by doing

    frame.$('.main')

这似乎是通过登录表单获取iframe的代码.

This is the code that seems to get the iframe with the login form.

    const browser = await puppeteer.launch({headless:false});
    const page = await browser.newPage();

    await page.goto('http://www.espn.com/login')
    await page.waitForSelector("iframe");

    const elementHandle = await page.$('div#disneyid-wrapper iframe');
    const frame = await elementHandle.contentFrame();
    await browser.close()

我希望能够访问iframe元素内的用户名字段,密码字段和登录按钮.每当我尝试访问这些字段时,都会返回null.

I want to be able to access the username field, password field, and the login button within the iframe element. Whenever I try to access these fields, I get a return of null.

推荐答案

您可以像现在一样使用contentFrame获取iframe,然后调用$.

You can get the iframe using contentFrame as you are doing now, and then call $.

const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();

await page.goto('http://www.espn.com/login')
await page.waitForSelector("iframe");

const elementHandle = await page.$('div#disneyid-wrapper iframe');
const frame = await elementHandle.contentFrame();
await frame.waitForSelector('[ng-model="vm.username"]');
const username = await frame.$('[ng-model="vm.username"]');
await username.type('foo');
await browser.close()

这篇关于如何在Puppeteer中的iframe元素中选择元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆