如何在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.
我已经按照一些指南和 使用入门页面:第一行有一条说明可以运行:
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中运行JavaScript代码 WebDriver
,改为:
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');");
您可以在此找到更多文档此处,在文档中,或者,最好是 JavascriptExecutor 的JavaDocs中的api / java / org / openqa / selenium / JavascriptExecutor.htmlrel =noreferrer>。
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:
// 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屋!