简体   繁体   中英

With Puppeteer: How can I get an iframe from its parent element selector?

I want to get an iframe as frame and click an element in the frame, but the iframe does not have a name and the website has many frames ( page.frames() returns 14).

And I don't have permission to edit html. I can only edit the JavaScript.

I think the best way to identify the iframe in this case is from its parent element.

How can I do this with puppeteer?

<div id="foo">
  <iframe>
    #document
  </iframe>
</div>

Note that you should also add these browser startup options to run contentFrame method, otherwise it will return null:

const browser = await puppeteer.launch({
    headless: false,
    args: [
      '--disable-web-security',
      '--disable-features=IsolateOrigins,site-per-process'
    ]
});

You can use the elementHandle.contentFrame() function to return a frame from an element handle.

Quote from the docs:

Resolves to the content frame for element handles referencing iframe nodes, or null otherwise

Example:

const elementHandle = await page.$('div#foo iframe');
const frame = await elementHandle.contentFrame();

Having an id of any element you can easily loop through its children and find all, that fulfill specific criteria, for example being an iframe.
Filter function cannot be used, since this is not an Array, but a NodeList.

 var parent = document.getElementById("foo"); var iframes = []; for(var i = 0; i < parent.children.length; i++){ var child = parent.children[i]; if(child.localName == 'iframe'){ iframes.push(child); } }; console.log(iframes)
 <div id="foo"> <iframe> #document </iframe> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM