javascript - 单击具有特定样式的 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');
}
});
解决方案
如果样式非常具体,您可以轻松找到一个元素。无需为此遍历所有帧。
const selector = `iframe[style*="display: block"]`
const visibleIframe = document.querySelector(selector);
console.log({ visibleIframe });
单击内部的按钮可以通过多种方式完成。这是一个普通的javascript解决方案,
visibleIframe.contentDocument.querySelector(".button").click()
推荐阅读
- python - 如何使用 sklearn 中的 GridSearchCV 设置自己的评分以进行回归?
- mysql - 使用左连接列出帐号、余额、贷款号码和金额地址
- scala - 用于异步映射响应的自定义 Akka HTTP 指令
- android - 可展开的列表视图子点击新活动
- python-3.x - Raspberry Pi,套接字错误“socket.gaierror:[Errno -3] 名称解析暂时失败”
- python - 我怎么能从浮点数格式化一个python字符串并固定长度和宽度
- python - python循环,金字塔模式
- c++ - QTabWidget 增加标签滚动条箭头按钮宽度
- syntax-error - 无法找出 glpk 模型中表达式中的语法错误
- javascript - 无需滚动即可在所有平台上的视口中调整所有元素