我有一个包含大约 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>
我的问题是如何在 puppeteer 中选择具有 display: block
样式的 iframe,然后单击其中的按钮。
我试图通过获取页面上的所有 iframe 来解决这个问题,然后循环并选择显示样式为“ block ”的 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');
}
});
最佳答案
如果样式非常具体,您可以轻松找到一个元素。无需为此遍历所有帧。
const selector = `iframe[style*="display: block"]`
const visibleIframe = document.querySelector(selector);
console.log({ visibleIframe });
单击里面的按钮可以通过多种方式完成。这是一个普通的 javascript 解决方案,
visibleIframe.contentDocument.querySelector(".button").click()
关于javascript - 单击具有特定样式的 iframe,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68731100/