您如何使用 Selenium 在框架内执行 javascript?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2767690/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 12:36:48  来源:igfitidea点击:

How do you use Selenium to execute javascript within a frame?

javajavascripttestingiframeselenium

提问by Zee Spencer

I have a page (index.html) which has a frame:

我有一个页面(index.html),它有一个框架:

<html>
<body>
<iframe src="otherPage.html" />
</body>
</html>

And the otherPage.html has the contents:

otherPage.html 有以下内容:

<html>
<head><link src="jquery-min.js" type="text/javascript" /></head>
<body><div id="main">Contents</div></body>
</html>

I am attempting to use the following selenium code on index.html:

我正在尝试在 index.html 上使用以下 selenium 代码:

selenium.open("index.html");
selenium.selectFrame("//iframe");
selenium.getEval("window.jQuery('div[id=main]')");

However this fails miserably. It says that the jQuery object doesn't exist.

然而,这惨败。它说 jQuery 对象不存在。

If I attempt to execute the selenium test on the otherPage like so:

如果我尝试在 otherPage 上执行 selenium 测试,如下所示:

selenium.open("otherPage.html");
selenium.getEval("window.jQuery('div[id=main]')");

everything is hunky dory.

一切都是笨拙的多莉。

Right now this is pseudo code, if people want me to make it compile I'll do that and put it on github.

现在这是伪代码,如果人们想让我编译它,我会这样做并将其放在 github 上。

采纳答案by AutomatedTester

Selenium stores the Window Object within its own object so it can manipulate it better. Once you move to the frame it should be like this.

Selenium 将 Window 对象存储在它自己的对象中,以便更好地操作它。一旦你移动到框架它应该是这样的。

selenium.getEval("var window = this.browserbot.getUserWindow();window.jQuery('div[id=main]')");

And that should work for you

这应该对你有用

I have a tutorial on my site for this type of situation here

我有我的网站教程这种类型的情况在这里

回答by Innovation

You can use :

您可以使用 :

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("javascript:sendEvent('play');");