如何在 Selenium WebDriver Java 中使用 JavaScript [英] How to use JavaScript with Selenium WebDriver Java
问题描述
我想在使用 Java 的 WebDriver (Selenium 2) 中使用 JavaScript.
I want to use JavaScript with WebDriver (Selenium 2) using Java.
我遵循了一些指南和入门 page:在第一行有一条指令可以作为:
I've followed some a guide and on Getting Started page: there is an instruction at 1st line to run as:
$ ./go webdriverjs
我的问题:上面提到的命令将从哪个文件夹/位置运行/执行?
My question: From which folder/location the command mentioned above will be run/executed?
推荐答案
根据您之前的问题,我想您想从 Java 的 WebDriver
运行 JavaScript 片段.如果我错了,请纠正我.
Based on your previous questions, I suppose you want to run JavaScript snippets from Java's WebDriver
. Please correct me if I'm wrong.
WebDriverJs
实际上只是"另一个 WebDriver
语言绑定(你可以用 Java、C#、Ruby、Python、JS 和现在可能更多的语言编写你的测试).这尤其是 JavaScript,因此您可以使用 JavaScript 编写测试.
The WebDriverJs
is actually "just" another WebDriver
language binding (you can write your tests in Java, C#, Ruby, Python, JS and possibly even more languages as of now). This one, particularly, is JavaScript, and allows you therefore to write tests in JavaScript.
如果您想在 Java WebDriver
中运行 JavaScript 代码,请改为这样做:
If you want to run JavaScript code in Java WebDriver
, do this instead:
WebDriver driver = new AnyDriverYouWant();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor)driver).executeScript("yourScript();");
} else {
throw new IllegalStateException("This driver does not support JavaScript!");
}
我也喜欢这样做:
WebDriver driver = new AnyDriverYouWant();
JavascriptExecutor js;
if (driver instanceof JavascriptExecutor) {
js = (JavascriptExecutor)driver;
} // else throw...
// later on...
js.executeScript("return document.getElementById('someId');");
您可以在此处的文档中找到更多文档,或者最好是 inJavascriptExecutor
的 JavaDocs.
You can find more documentation on this here, in the documenation, or, preferably, in the JavaDocs of JavascriptExecutor
.
executeScript()
也接受函数调用和原始 JS.你可以从它返回
一个值,你可以向它传递许多复杂的参数,一些随机的例子:
The executeScript()
takes function calls and raw JS, too. You can return
a value from it and you can pass lots of complicated arguments to it, some random examples:
1.
// returns the right WebElement
// it's the same as driver.findElement(By.id("someId"))
js.executeScript("return document.getElementById('someId');");
// draws a border around WebElement
WebElement element = driver.findElement(By.anything("tada"));
js.executeScript("arguments[0].style.border='3px solid red'", element);
// changes all input elements on the page to radio buttons
js.executeScript(
"var inputs = document.getElementsByTagName('input');" +
"for(var i = 0; i < inputs.length; i++) { " +
" inputs[i].type = 'radio';" +
"}" );
这篇关于如何在 Selenium WebDriver Java 中使用 JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!