首页 > 解决方案 > 单击具有特定样式的 iframe

问题描述

我有一个包含大约 10 个 iframe 的页面。这些 iframe 中只有 1 个是可见的,并且可见 iframe 的索引在每次页面重新加载时都会更改。可见的 iframe 仅包含 的样式display: block,它不包含我可以用来选择它的任何其他内容,例如名称或标题。

例子:

<div class="container">
    <iframe style="display: none; width: 310px; height: 100px; border: 0px; 
    user-select: none;">
       <html>
         <body>
           <div class="button"/>
         </body>
       </html>
     </iframe> <--- not visible 
        
    <iframe style="display: block; width: 310px; height: 100px; border: 0px; 
    user-select: none;">
       <html>
         <body>
           <div class="button"/> // need to click this!
         </body>
       </html>
     </iframe> <--- visible :)
</div>

我的问题是如何display: block在 puppeteer 中选择具有样式的 iframe,然后单击其中的按钮。

我试图通过获取页​​面上的所有 iframe,然后循环并选择显示样式为“块”的 iframe 来解决此问题:

 // select all iframes
 const Frames = await page.frames(); 
  
  // loop over iframes and check if iframe display is block or none.
  Frames.forEach(async (item, i) => {
    const frame = await item.contentFrame();
    const showingIframe = await page.evaluate(
      () => window.getComputedStyle(frame.querySelector('iframe')).display
    );

    if (showingIframe === 'block') {
      console.log('showing');
      // click button
    } else {
      console.log('not showing');
    }
  });

标签: javascriptpuppeteercaptcha

解决方案


如果样式非常具体,您可以轻松找到一个元素。无需为此遍历所有帧。

const selector = `iframe[style*="display: block"]`
const visibleIframe = document.querySelector(selector);
console.log({ visibleIframe });

单击内部的按钮可以通过多种方式完成。这是一个普通的javascript解决方案,

visibleIframe.contentDocument.querySelector(".button").click()

推荐阅读