Javascript iframe内Web元素的QuerySelector
编辑:新标题。 我要找的是iframe中元素的document.querySelector 我在谷歌上搜索了很多答案,最后我被难住了 我试图在iframe中进行查询。我正在构建用于Selenium的字符串选择器,通常我只是用Firebug检查元素,然后使用document.querySelectorAll(“theStringUID”) 但它不适用于iframe中的元素。我已经尝试了下面的所有方法,以在“page iframe”iframe中获取元素“radiobutton1”Javascript iframe内Web元素的QuerySelector,javascript,html,iframe,selenium-webdriver,css-selectors,Javascript,Html,Iframe,Selenium Webdriver,Css Selectors,编辑:新标题。 我要找的是iframe中元素的document.querySelector 我在谷歌上搜索了很多答案,最后我被难住了 我试图在iframe中进行查询。我正在构建用于Selenium的字符串选择器,通常我只是用Firebug检查元素,然后使用document.querySelectorAll(“theStringUID”) 但它不适用于iframe中的元素。我已经尝试了下面的所有方法,以在“page iframe”iframe中获取元素“radiobutton1” 谢谢-如果原始页
谢谢-如果原始页面的url与iframe内容不在同一个域中,javascript会将iframe视为一个黑匣子,这意味着它不会看到其中的任何内容。简单es6改编自:
下面是一个跳转到相同原点帧(即兼容ES5)的片段:
函数findInFramesRec(选择器,文档){
var hit=doc.querySelector(选择器);
如果(命中)返回命中;
var frames=Array.prototype.slice.call(doc.frames);
对于(var i=0;(i
这将深入到框架集框架和iFrame中。它甚至可能存活(尽管未进入)跨原点帧。您可以执行以下操作:
document.querySelector(“iframe”).contentWindow.document.querySelector(“按钮”)
您是否在iframe加载完成之前运行脚本?如果您在console.log contentWindow中运行,会得到什么结果?如果您使用selenium,则需要调用switchTo().frame(“框架id”),然后运行您的代码。我已经为此工作了两个小时,所以我认为页面已完成加载:),并且我没有使用selenium编写查询,我正在尝试在Firebug控制台中编写查询。知道如何编写控制台查询来访问iframe中的元素吗?没错。请参阅此问题:未捕获的安全性错误:阻止来源为“”的帧访问来源为“”的帧。协议、域和端口必须匹配。“,来源:(1)您确定iframe内外的域相同吗?我不知道Selenium,但使用Puppeter,您可以在启动参数中传递“-disable web security”,并访问跨源帧。只需与typescript共享一个工作示例:document.getElementById(“…”[“contentWindow”].document.queryselectoral(“…”).Ty!
var elem1 = ".page-iframe";
console.log(elem1);
var elem2 = ".radiobutton1";
console.log(elem2);
document.querySelectorAll(elem1+elem2+"");
document.querySelectorAll('.page-iframe').contentWindow.document.body.querySelectorAll('.radiobutton1')
document.getElementById('.page-iframe').contentWindow.document.body.innerHTML;
[].forEach.call( document.querySelectorAll('.page-iframe'),
function fn(elem){
console.log(elem.contentWindow.document.body.querySelectorAll('.radiobutton1')); });
var contentWindow = document.getElementById('.page-iframe').contentWindow
var contentWindow = document.querySelectorAll('.page-iframe')
var contentWindow = document.querySelectorAll('.page-iframe')[0].contentWindow
document.querySelectorAll('iframe').forEach( item =>
console.log(item.contentWindow.document.body.querySelectorAll('a'))
)
function findInFramesRec(selector, doc) {
var hit = doc.querySelector(selector);
if (hit) return hit;
var frames = Array.prototype.slice.call(doc.frames);
for(var i = 0; (i < frames.length) && !hit ; i++) {
try {
if (!frames[i] || !frames[i].document) continue;
hit = findInFramesRec(selector, frames[i].document);
} catch(e) {}
}
return hit;
}