Feature-rich jQuery-like Java interface for Selenium WebDriver
seleniumQuery is a feature-rich cross-driver Java library that brings a jQuery-like interface for Selenium WebDriver.
It is designed to be a thin layer over Selenium. You can use seleniumQuery to manage the WebDriver for you, or you can use seleniumQuery on top of your favorite selenium framework just to make some cases simpler when needed.
Example snippet:
// Regular SeleniumWebElement el = driver.findElement(By.cssSelector(".street"));
String oldStreet = element.getAttribute("value"); // what if ".street" is a <select>? this won't work
element.setAttribute("value", "4th St!")
// seleniumQuery// getting the valueString oldStreet = $(".street").val(); // works even if it is a <select>, <textarea>, etc.// setting the value
$("input.street").val("4th St!"); // also would work for a <select>
And much more. The example above is of something that has an equivalent in Selenium. Not everything does (many things would require tons of boilerplate in vanilla Selenium).
No special configuration needed - use seleniumQuery's goodies in your project right now:
// an existing WebDriver...WebDriver driver =newFirefoxDriver();
// set it up
$.driver().use(driver);
// and use all the goodsfor (WebElement e: $(".myClass:contains('My Text!'):not(:button)")) {
System.out.println("That element: "+ e);
}
and even some own seleniumQuery selectors: $("#myOldDiv").is(":not(:present)").
Built using Selenium WebDriver's capabilities, no jQuery.js is embedded at the page, no side-effects are generated.
Quickstart: A running example
Try it out now with the running example below:
import staticio.github.seleniumquery.SeleniumQuery.$; // this will allow the short syntaxpublicclassSeleniumQueryExample {
publicstaticvoidmain(String[] args) {
// The WebDriver will be instantiated only when first used
$.driver()
.useChrome() // sets Chrome as the driver (this is optional, if omitted, will default to HtmlUnit)
.headless() // configures chrome to be headless
.autoDriverDownload() // automatically downloads and configures chromedriver.exe
.autoQuitDriver(); // automatically quits the driver when the JVM shuts down// or, instead, use any previously existing driver// $.driver().use(myExistingInstanceOfWebDriver);// starts the driver (if not started already) and opens the URL
$.url("http://www.google.com/?hl=en");
// interact with the page
$(":text[name='q']").val("seleniumQuery"); // the keys are actually typed!// Besides the short syntax and the jQuery behavior you already know,// other very useful function in seleniumQuery is .waitUntil(),// handy for dealing with user-waiting actions (specially in Ajax enabled pages):// the command below waits until the button is visible and then performs a real user click (not just the JS event)
$(":button[value='Google Search']").waitUntil().isVisible().then().click();
// this waits for the #resultStats to be visible using a selector and, when it is visible, returns its text contentString resultsText = $("#resultStats").waitUntil().is(":visible").then().text();
// .assertThat() functions: fluently asserts that the text contains the string "seconds", ignoring case
$("#resultStats").assertThat().text().containsIgnoreCase("seconds");
System.out.println(resultsText);
// should print something like: About 4,100 results (0.42 seconds)// $.quit(); // would quit the driver, but it is not needed as .autoQuitDriver() was used
}
}
To get the latest version of seleniumQuery, add to your pom.xml:
Download and execute the seleniumQuery showcase project. It contains many demonstrations of what seleniumQuery is capable of.
Features
seleniumQuery implements all jQuery functions that are useful to browser manipulation. On top of it, we add many other useful functions (see $("selector").waitUntil() and $("selector").assertThat() below).
Our main goal is to make emulating user actions and reading the state of pages easier than ever, with a consistent behavior across drivers.
Readable jQuery syntax you already know
Make your code/tests more readable and easier to maintain. Leverage your knowledge of jQuery.
// Instead of regular Selenium code:WebElement element = driver.findElement(By.id("mySelect"));
newSelect(element).selectByValue("ford");
// You can have the same effect writing just:
$("#mySelect").val("ford");
Get to know what jQuery functions seleniumQuery supports and what else it brings to the table on our seleniumQuery API wiki page.
Waiting (ajax testing) and asserting
WebDriver's FluentWait is great, but it requires too much boilerplate code. Enters the .waitUntil() function:
// Below is an example of a <div> that should be hidden as effect of an Ajax call.// The code will hold until the modal is gone. If it is never gone, seleniumQuery will throw a timeout exception
$("#modalDiv :button:contains('OK')").click();
$("#modalDiv :button:contains('OK')").waitUntil().is(":not(:visible)");
// Or the two commands above, fluently:
$("#modalDivOkButton").click().waitUntil().is(":not(:visible)");
You can also assert directly into the seleniumQuery object using .assertThat():
Any function that can be used with $().waitUntil() can also be used with $().assertThat() and vice-versa. See below, expand (click on the arrow) each item for more details.
$(). function
Property/Evaluation Function
Evaluation Function
.waitUntil()
In order to handle interactions with Ajax-enabled pages, you can use the .waitUntil() function:
The .waitUntil() functions will requery the DOM for the elements until the given condition is met, returning a new seleniumQuery object when that happens.
// .waitUntil() will requery the DOM every time until the matched set fulfills the requirements// .is() functions
$(".aDivDiv").waitUntil().is(":present");
$(".myInput").waitUntil().is(":enabled");
$(".aDivDiv").waitUntil().is(":visible");
$(".myInput").waitUntil().is(":visible:enabled");
// functions such as .val(), .text() and others are also available
$(".myInput").waitUntil().val().isEqualTo("expectedValue");
$(".aDivDiv").waitUntil().text().contains("expectedText");
// and more...
$(".myInput").waitUntil().val().matches(".*\d{10}\*");
$(".myInput").waitUntil().size().isGreaterThan(7);
$(".aDivDiv").waitUntil().html().contains("<div>expected</div>");
.assertThat()
Asserts, fluently, that the function has a specified value or matches a specified condition.
Evaluates if this seleniumQuery object has only visible elements.
Note: this is different from .is(":visible") because .is() requires only one element to match the selector (to be visible), whereas this .isVisible() method requires all matched elements to be visible.
Evaluates if this seleniumQuery object has only visible elements.
Note: this is different from .is(":visible") because .is() requires only one element to match the selector (to be visible), whereas this .isVisible() method requires all matched elements to be visible.
$("span").assertThat().size().isGreaterThan(5).and().text().isEqualTo("a b c d e");
Or use functions after waiting/asserting using .then():
$("#div").waitUntil().isVisible().then().click();
Flexible WebDriver builder system
How to setup the WebDriver? Simply use our builder. You can download their executables before or you can let seleniumQuery automatically download and configure them. Setup in seleniumQuery is all too easy:
// Using Chrome, general example:
$.driver()
.useChrome() // configures Chrome as the driver
.headless() // configures Chrome to run in headless mode
.autoDriverDownload() // automatically downloads and configures chromedriver.exe
.autoQuitDriver(); // automatically quits the driver when the JVM shuts down// Using Firefox
$.driver()
.useFirefox() // configures Firefox as the driver
.headless() // configures Firefox to run in headless mode
.autoDriverDownload() // automatically downloads and configures geckodriver.exe
.autoQuitDriver(); // automatically quits the driver when the JVM shuts down
For more examples, options and all supported drivers, see table below.
Using seleniumQuery in an existingWebDriver instance
The driver builder functions are a bonus, you don't have to use them. For seleniumQuery, it makes no difference.
If you want to create the WebDriver yourself or add seleniumQuery to an existing WebDriver instance just:
WebDriver myExistingDriverInstance =...; // created elsewhere by whoever
$.driver().use(myExistingDriverInstance); // from now on, $ will work on myExistingDriverInstance// now you can use all of seleniumQuery's power!
$("#phone").assertThat().val().isEqualTo("99887766");
Chrome
Here's how seleniumQuery can simplify a ChromeDriver instantiation.
Configures Chrome as the driver to be used. Provides additional configuration options that can be chained.
Calling $.driver().useChrome() does not instantiate the driver right away, it merely configures it. The driver will be instantiated when first used only (e.g. when $.url("http://somepage") is called).
.headless()
Runs Chrome in headless mode.
.autoQuitDriver()
Automatically quits the driver upon JVM shutdown.
If you don't use .autoQuitDriver(), you can quit the driver calling $.quit().
Having .autoQuitDriver() on and still calling $.quit() makes no harm, so quit at will.
.autoDriverDownload()
seleniumQuery automatically downloads and configures the driver. The download is managed by webdrivermanager. Additional options are available, pass a lambda to .autoDriverDownload(<labda>) to be able to configure:
$.driver().useChrome().autoDriverDownload((BrowserManager configurer) -> {
// se more options at https://github.com/bonigarcia/webdrivermanager#webdrivermanager-api
configurer.proxy("http://corpproxy:8182");
configurer.proxyUser("myUser");
configurer.proxyPass("myPass")
});
.withOptions(ChromeOptions)
Enables additional configuration through a ChromeOptions instance.
.withPathToChromeDriver(String)
If you don't want seleniumQuery to automatically download the executable for you (using .autoDriverDownload()) you can specify the location of chromedriver.exe/chromedriver yourself:
If you use neither .autoDriverDownload() nor .withPathToChromeDriver(), seleniumQuery will attempt to find the executable on your PATH or classpath. If it doesn't find it anywhere, an exception will be thrown.
.withCapabilities(DesiredCapabilities)
Configures the given DesiredCapabilities in the driver to be instantiated. Prefer ChromeOptions when possible.
// Using Chrome
$.driver().useChrome(); // will look for chromedriver/exe to you, including in the classpath!// if you don't have chromedriver.exe and want seleniumQuery to auto download and configure it
$.driver().useChrome().headless().autoDriverDownload();
// If you want to set the path to chromedriver.exe yourself
$.driver().useChrome().withPathToChromeDriver("path/to/chromedriver.exe")
// General example:
$.driver()
.useChrome() // configures Chrome as the driver
.headless() // configures Chrome to run in headless mode
.autoDriverDownload() // automatically downloads and configures chromedriver.exe
.autoQuitDriver(); // automatically quits the driver when the JVM shuts down// using options
$.driver()
.useChrome()
.withOptions(<some ChromeOptions instance>)
Firefox
Easy FirefoxDriver instantiation and configuration with seleniumQuery.
Configures Firefox as the driver to be used. Provides additional configuration options that can be chained.
Calling $.driver().useFirefox() does not instantiate the driver right away, it merely configures it. The driver will be instantiated when first used only (e.g. when $.url("http://somepage") is called).
.headless()
Runs Firefox in headless mode.
.autoQuitDriver()
Automatically quits the driver upon JVM shutdown.
If you don't use .autoQuitDriver(), you can quit the driver calling $.quit().
Having .autoQuitDriver() on and still calling $.quit() makes no harm, so quit at will.
.autoDriverDownload()
seleniumQuery automatically downloads and configures the driver. The download is managed by webdrivermanager. Additional options are available, pass a lambda to .autoDriverDownload(<labda>) to be able to configure:
$.driver().useFirefox().autoDriverDownload((BrowserManager configurer) -> {
// se more options at https://github.com/bonigarcia/webdrivermanager#webdrivermanager-api
configurer.proxy("http://corpproxy:8182");
configurer.proxyUser("myUser");
configurer.proxyPass("myPass")
});
.withOptions(FirefoxOptions)
Enables additional configuration through a FirefoxOptions instance.
.withBinary(FirefoxBinary)
Enables additional configuration through a FirefoxBinary instance.
.withProfile(FirefoxProfile)
Enables additional configuration through a FirefoxProfile instance.
.withCapabilities(DesiredCapabilities)
Configures the given DesiredCapabilities in the driver to be instantiated. Prefer FirefoxOptions when possible.
// Using Firefox
$.driver()
.useFirefox() // configures Firefox as the driver
.headless() // configures Firefox to run in headless mode
.autoDriverDownload() // automatically downloads and configures geckodriver.exe
.autoQuitDriver(); // automatically quits the driver when the JVM shuts down// simplified setting of profile, options and binary
$.driver()
.useFirefox()
.withProfile(<an instance of FirefoxProfile>)
.withOptions(<an instance of FirefoxOptions>)
.withBinary(<an instance of FirefoxBinary>);
Opera
Automatic driver download available.
.useOpera()
Configures Opera as the driver to be used. Provides additional configuration options that can be chained.
Calling $.driver().useOpera() does not instantiate the driver right away, it merely configures it. The driver will be instantiated when first used only (e.g. when $.url("http://somepage") is called).
.autoQuitDriver()
Automatically quits the driver upon JVM shutdown.
If you don't use .autoQuitDriver(), you can quit the driver calling $.quit().
Having .autoQuitDriver() on and still calling $.quit() makes no harm, so quit at will.
.autoDriverDownload()
seleniumQuery automatically downloads and configures the driver. The download is managed by webdrivermanager. Additional options are available, pass a lambda to .autoDriverDownload(<labda>) to be able to configure:
$.driver().useOpera().autoDriverDownload((BrowserManager configurer) -> {
// se more options at https://github.com/bonigarcia/webdrivermanager#webdrivermanager-api
configurer.proxy("http://corpproxy:8182");
configurer.proxyUser("myUser");
configurer.proxyPass("myPass")
});
.withOptions(OperaOptions)
Enables additional configuration through a OperaOptions instance.
.withBinary(string | File)
Configures the Opera browser binary location. Example:
Configures the given DesiredCapabilities in the driver to be instantiated. Prefer OperaOptions when possible.
// Opera// we'll download the driver for you
$.driver().useOpera().autoDriverDownload();
// simplified setting of options and binary
$.driver()
.useOpera()
.withOptions(<an instance of OperaOptions>)
.withBinary("C:/Program Files/Opera/49.0.2725.47/opera.exe") // example path
.autoDriverDownload();
Configures PhantomJS as the driver to be used. Provides additional configuration options that can be chained.
Calling $.driver().usePhantomJS() does not instantiate the driver right away, it merely configures it. The driver will be instantiated when first used only (e.g. when $.url("http://somepage") is called).
.autoQuitDriver()
Automatically quits the driver upon JVM shutdown.
If you don't use .autoQuitDriver(), you can quit the driver calling $.quit().
Having .autoQuitDriver() on and still calling $.quit() makes no harm, so quit at will.
.autoDriverDownload()
seleniumQuery automatically downloads and configures the driver. The download is managed by webdrivermanager. Additional options are available, pass a lambda to .autoDriverDownload(<labda>) to be able to configure:
$.driver().usePhantomJS().autoDriverDownload((BrowserManager configurer) -> {
// se more options at https://github.com/bonigarcia/webdrivermanager#webdrivermanager-api
configurer.proxy("http://corpproxy:8182");
configurer.proxyUser("myUser");
configurer.proxyPass("myPass")
});
.withPathToPhantomJS(String)
If you don't want seleniumQuery to automatically download the executable for you (using .autoDriverDownload()) you can specify the location of phantomjs.exe/phantomjs yourself:
If you use neither .autoDriverDownload() nor .withPathToPhantomJS(), seleniumQuery will attempt to find the executable on your PATH or classpath. If it doesn't find it anywhere, an exception will be thrown.
.withCapabilities(DesiredCapabilities)
Configures the given DesiredCapabilities in the driver to be instantiated.
// PhantomJS (GhostDriver)// we'll download phantomjs.exe for you
$.driver().usePhantomJS().autoDriverDownload();
// or, we may find phantomjs[.exe] for you, throwing an error if not present
$.driver().usePhantomJS();
// Or you may set the path yourself
$.driver().usePhantomJS().withPathToPhantomJS("path/to/phantomjs.exe");
HmtlUnit
Always headless, java-based. No need to download anything.
.useHtmlUnit()
Configures HmtlUnit as the driver to be used. Provides additional configuration options that can be chained.
Calling $.driver().useHtmlUnit() does not instantiate the driver right away, it merely configures it. The driver will be instantiated when first used only (e.g. when $.url("http://somepage") is called).
.autoQuitDriver()
Automatically quits the driver upon JVM shutdown.
If you don't use .autoQuitDriver(), you can quit the driver calling $.quit().
Having .autoQuitDriver() on and still calling $.quit() makes no harm, so quit at will.
Note: Since HtmlUnit is a java-based driver, it will quit upon JVM shutdown anyway.
.withoutJavaScript()
Runs HtmlUnit with disabled JavaScript.
.emulatingChrome()
Configures HtmlUnit to emulate Chrome.
.emulatingFirefox()
Configures HtmlUnit to emulate Firefox.
.emulatingInternetExplorer()
Configures HtmlUnit to emulate Internet Explorer.
.withCapabilities(DesiredCapabilities)
Configures the given DesiredCapabilities in the driver to be instantiated.
// There are many possibilities to set up HtmlUnitDriver// HtmlUnit default (Chrome/JavaScript ON)
$.driver().useHtmlUnit();
// Want disabled JavaScript, just call .withoutJavaScript()
$.driver().useHtmlUnit().withoutJavaScript();
// HtmlUnit emulating Chrome
$.driver().useHtmlUnit().emulatingChrome();
$.driver().useHtmlUnit().emulatingChrome().withoutJavaScript();
// HtmlUnit emulating Firefox
$.driver().useHtmlUnit().emulatingFirefox(); // could disable JS here as well// And IE
$.driver().useHtmlUnit().emulatingInternetExplorer11(); // JS is disableable as well
$.driver().useHtmlUnit().emulatingInternetExplorer(); // will pick latest IE
Safari
seleniumQuery tests Safari as a remote driver.
$.driver().useDriver(newSafariDriver());
Edge
Automatic driver download available.
.useEdge()
Configures Edge as the driver to be used. Provides additional configuration options that can be chained.
Calling $.driver().useEdge() does not instantiate the driver right away, it merely configures it. The driver will be instantiated when first used only (e.g. when $.url("http://somepage") is called).
.autoQuitDriver()
Automatically quits the driver upon JVM shutdown.
If you don't use .autoQuitDriver(), you can quit the driver calling $.quit().
Having .autoQuitDriver() on and still calling $.quit() makes no harm, so quit at will.
.autoDriverDownload()
seleniumQuery automatically downloads and configures the driver. The download is managed by webdrivermanager. Additional options are available, pass a lambda to .autoDriverDownload(<labda>) to be able to configure:
$.driver().useEdge().autoDriverDownload((BrowserManager configurer) -> {
// se more options at https://github.com/bonigarcia/webdrivermanager#webdrivermanager-api
configurer.proxy("http://corpproxy:8182");
configurer.proxyUser("myUser");
configurer.proxyPass("myPass")
});
.withOptions(EdgeOptions)
Enables additional configuration through a EdgeOptions instance.
.withCapabilities(DesiredCapabilities)
Configures the given DesiredCapabilities in the driver to be instantiated. Prefer EdgeOptions when possible.
// Edge// we'll download the driver for you
$.driver().useEdge().autoDriverDownload();
// simplified setting of options
$.driver()
.useEdge()
.withOptions(<an instance of EdgeOptions>);
Configures Internet Explorer as the driver to be used. Provides additional configuration options that can be chained.
Calling $.driver().useInternetExplorer() does not instantiate the driver right away, it merely configures it. The driver will be instantiated when first used only (e.g. when $.url("http://somepage") is called).
.autoQuitDriver()
Automatically quits the driver upon JVM shutdown.
If you don't use .autoQuitDriver(), you can quit the driver calling $.quit().
Having .autoQuitDriver() on and still calling $.quit() makes no harm, so quit at will.
.autoDriverDownload()
seleniumQuery automatically downloads and configures the driver. The download is managed by webdrivermanager. Additional options are available, pass a lambda to .autoDriverDownload(<labda>) to be able to configure:
$.driver().useInternetExplorer().autoDriverDownload((BrowserManager configurer) -> {
// se more options at https://github.com/bonigarcia/webdrivermanager#webdrivermanager-api
configurer.proxy("http://corpproxy:8182");
configurer.proxyUser("myUser");
configurer.proxyPass("myPass")
});
.withPathToIEDriverServerExe(String)
If you don't want seleniumQuery to automatically download the executable for you (using .autoDriverDownload()) you can specify the location of IEDriverServer.exe yourself:
If you use neither .autoDriverDownload() nor .withPathToIEDriverServerExe(), seleniumQuery will attempt to find IEDriverServer.exe on your PATH or classpath. If it doesn't find it anywhere, an exception will be thrown.
.withCapabilities(DesiredCapabilities)
Configures the given DesiredCapabilities in the driver to be instantiated.
// InternetExplorerDriver// we'll download the driver for you
$.driver().useInternetExplorer().autoDriverDownload();
// or we search IEDriverServer.exe on your computer (path and classpash) for you
$.driver().useInternetExplorer();
// Or you set the path yourself
$.driver().useInternetExplorer().withPathToIEDriverServerExe("C:\\IEDriverServer.exe");
seleniumQuery still is Selenium - with "just" a jQuery interface
So there is a important aspect of it: Although our functions yield the same result as if you were using jQuery, remember we always execute them from the user perspective. In other words, when you call:
We don't change the value attribute directly like jQuery does. We actually do as a user would: We clear the input and type, key by key, the string provided as argument!
And we go the extra mile whenever possible:
Our $().val() even works on contenteditable elements AND documentMode=on <iframe>s: They don't have value, but we type the text in them, again, key by key, as an user would;
If it is an <input type="file"> we select the file;
When the element is a <select>, we choose the <option> by the value given (same as $("selector").as().select().selectByValue("123")).
Always from the user perspective
On the same tone, when selecting/checking <option>s or checkboxes or radios, try not to use $().prop("selected", true) directly to them (which to work, of course, would need JS to be enabled on the driver). Do as an user would: call .click()! Or, better yet, use seleniumQuery's .as().select() functions: $().as().select().selectByVisibleText("My Option") or $().as().select().selectByValue("123").
Using multiple browsers/drivers simultaneously
Typically, the $ is a static variable, thus every command you issue only affects the one same instance of WebDriver.
But... what if you want/need to use two WebDrivers at the same time?
publicstaticvoid main(String[] args) {
String demoPage ="https://cdn.rawgit.com/seleniumQuery/seleniumQuery-showcase/master/Agent.html";
// using two drivers (chrome and firefox) at the same timeSeleniumQueryBrowser chrome =newSeleniumQueryBrowser();
chrome.$.driver().useHtmlUnit().emulatingChrome().autoQuitDriver();
chrome.$.url(demoPage);
SeleniumQueryBrowser firefox =newSeleniumQueryBrowser();
firefox.$.driver().useHtmlUnit().emulatingFirefox().autoQuitDriver();
firefox.$.url(demoPage);
chrome.$("#agent").assertThat().text().contains("Chrome");
firefox.$("#agent").assertThat().text().contains("Firefox");
}
Plugin System
seleniumQuery supports plugins through the .as(PLUGIN) function, such as:
There are some default plugins. To check them out, call .as() without arguments. Example:
// the .select() plugin
$("#citiesSelect").as().select().selectByVisibleText("New York");
// picks an <option> in the <select> based in the <option>'s visible text
If the dollar symbol, $, gives you the yikes -- we know, it is used for internal class names --, it is important to notice that the $ symbol in seleniumQuery is not a class name, but a static method (and field). Still, if you don't feel like using it, you can resort to sQ() or good ol' jQuery() and benefit from all the same goodies:
The tool quite simple, so there's a lot of room for improvement. If you think something would be useful for you, it would probably be useful to us all, tell us what you're thinking!
I try to use seleniumQuery to navigate through a website with dynamically changed content (meaning it changes with page refresh). When I open the website in browser there is a button I need to click, but the button appears only after some time.
In Selenium IDE I use a waitForElementPresent command to wait for this button to appear before I fire it up. I tried the following code to copy this behaviour in seleniumQuery
$(".custom-dropdown-arrow-major").waitUntil().is(":present"); // tried also with :visible
But I receive following error:
Caused by: org.openqa.selenium.InvalidSelectorException: The given selector (.//[contains(concat(' ', normalize-space(@class), ' '), ' custom-dropdown-arrow-major ')]) is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Unable to locate an element with the xpath expression (.//[contains(concat(' ', normalize-space(@class), ' '), ' custom-dropdown-arrow-major ')]) because of the following error:
TypeError: Argument 1 of Document.createNSResolver is not an object.
Whereas in webdriver this work:
WebDriverWait wait = new WebDriverWait(driver.get(), 100);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("custom-dropdown-arrow-major")));
[Edit]
I assume problem starts with $ contructor, where right at the begininng elements are retrieved.
Would it make sense to make this attribute lazy initialized? In that case the exception would not be fired upon $().waitUntil() but at the same time it shouldn't affect the rest of code. I would be happy to make the change if you agree on solution.
Sometime we want not to close the current webdriver and switch between the driver then we cannot just do $.driver().use(webDriver); because it will automatically close the existing driver. So to make it easy we need an extra parameter for developer to either clear or not the existing driver before instantiating the new webdriver.
Every time that I want to use the $(element).val(text) in an element like this one:
I get the following error:
Caused by: org.openqa.selenium.WebDriverException: Element must be user-editable in order to clear it.
Build info: version: '2.51.0', revision: '1af067d', time: '2016-02-05 19:15:17'
System info: host: 'JordiPonss-MacBook-Pro-1194.local', ip: '192.168.38.180', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.5', java.version: '1.8.0_66'
Driver info: driver.version: unknown
Command duration or timeout: 500 milliseconds
Build info: version: '2.45.0', revision: '5017cb8e7ca8e37638dc3091b2440b90a1d8686f', time: '2015-02-27 09:10:26'
System info: host: 'JordiPonss-MacBook-Pro-1194.local', ip: '192.168.38.180', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11.5', java.version: '1.8.0_66'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=45.2.0, platform=MAC, nativeEvents=false, acceptSslCerts=true, webdriver.remote.sessionid=52a9201d-0867-4fa3-94e9-3202c5f8db5e, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: 52a9201d-0867-4fa3-94e9-3202c5f8db5e
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:268)
at org.openqa.selenium.remote.RemoteWebElement.clear(RemoteWebElement.java:113)
at io.github.seleniumquery.functions.jquery.forms.ValFunction.val(ValFunction.java:131)
at io.github.seleniumquery.functions.jquery.forms.ValFunction.val(ValFunction.java:87)
at io.github.seleniumquery.functions.SeleniumQueryFunctions.valueWrite(SeleniumQueryFunctions.java:59)
at io.github.seleniumquery.internal.SqObject.val(SqObject.java:164)
This is the html code for the iFrame:
Any idea of what is happening? I tried different element values but one of them is $(//*[@id='CQrte']/p).val("test") and before executing this line I changed to the correct iframe
I'm currently testing with seleniumQuery and Firefox 38.7 a test that checks for an invalid URL, then for a valid one, then for an invalid one, as it follows:
The first one throws an WebDriverException: Target URL InvalidURL is not well-formed. which is expected. The second one opens the validURL as expected. But the third one, instead of trying to open "InvalidURL", i opens "www.invalidurl.com", which is a valid URL, making the test to fail.
How can I attach EventFiringWebDriver to the webdriver.
EventFiringWebDriver is used to listen to the events in the browserdriver.
It is a wrapper over the webdriver initited as below
EventFiringWebDriver efwd = new EventFiringWebDriver(ie11);
efwd.register(new CustomEventLogger());
How can I get the efwd when i access the driver using $.driver().get()
Is there any way to check if some element has one condition or another one?
For example If I have an element that has a text or a value attribute it would be possible to sendKeys to that element and wait until the value or the text are the expected ones, something like $(element).val(text).waitUntil().text().isEqualTo(text).or().val().isEqualTo(text)
After clicking on some button, the element is already clicked, but the method throws a StaleElementException. This is reproducible on only some buttons in the page, but not on all of them.
I use a css selector that is unique in order to ensure that I click on the correct button.
The curious thing is that the Exception is thrown AFTER clicking the button, so the element is actually used.
This is the Stacktrace:
Caused by: org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:59:12'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11', java.version: '1.8.0_72'
Driver info: driver.version: unknown
Command duration or timeout: 3.43 seconds
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd10cf2c0560f637404c2d96164b67d9d67', time: '2015-10-09 13:08:06'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11', java.version: '1.8.0_72'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
Capabilities [{applicationCacheEnabled=true, rotatable=false, handlesAlerts=true, databaseEnabled=true, version=38.4.0, platform=MAC, nativeEvents=false, acceptSslCerts=true, webdriver.remote.sessionid=b76c649d-22d3-487a-8ba8-51a463afc67d, webStorageEnabled=true, locationContextEnabled=true, browserName=firefox, takesScreenshot=true, javascriptEnabled=true, cssSelectorsEnabled=true}]
Session ID: b76c649d-22d3-487a-8ba8-51a463afc67d
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:206)
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:158)
at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:647)
at org.openqa.selenium.remote.RemoteWebElement.execute(RemoteWebElement.java:326)
at org.openqa.selenium.remote.RemoteWebElement.click(RemoteWebElement.java:84)
at io.github.seleniumquery.functions.jquery.events.ClickFunction.click(ClickFunction.java:47)
at io.github.seleniumquery.SeleniumQueryObject.click(SeleniumQueryObject.java:321)
at biz.netcentric.at.selcq.spi.tools.InteractionHelper.clickAndWait(InteractionHelper.java:34)
at biz.netcentric.at.selcq.spi.tools.InteractionHelper.clickAndWait(InteractionHelper.java:30)
at biz.netcentric.at.selcq.frontends.touchui.PageCreatorImpl.createPage(PageCreatorImpl.java:23)
at biz.netcentric.at.selcq.frontends.touchui.Sites.createPage(Sites.java:77)
at biz.netcentric.at.selcq.impl.WebsitesImpl.createPage(WebsitesImpl.java:60)
at biz.netcentric.at.selcq.CreatePageTest.createPageWithParametersTest(CreatePageTest.java:48)
... 23 more
Caused by: org.openqa.selenium.remote.ScreenshotException: Screen shot has been taken
Build info: version: '2.48.2', revision: '41bccdd10cf2c0560f637404c2d96164b67d9d67', time: '2015-10-09 13:08:06'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11', java.version: '1.8.0_72'
Driver info: driver.version: RemoteWebDriver
at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:138)
... 34 more
Caused by: org.openqa.selenium.StaleElementReferenceException: Element not found in the cache - perhaps the page has changed since it was looked up
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd', time: '2015-10-09 19:59:12'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11', java.version: '1.8.0_72'
Driver info: driver.version: unknown
For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '2.48.2', revision: '41bccdd10cf2c0560f637404c2d96164b67d9d67', time: '2015-10-09 13:08:06'
System info: os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.11', java.version: '1.8.0_72'
Driver info: driver.version: unknown
at <anonymous class>.fxdriver.cache.getElementAt(resource://fxdriver/modules/web-element-cache.js:9351)
at <anonymous class>.Utils.getElementAt(file:///var/folders/wf/94b1wttd0v1b6t0md1pkllp80000gn/T/anonymous2009414429332203653webdriver-profile/extensions/[email protected]/components/command-processor.js:8978)
at <anonymous class>.fxdriver.preconditions.visible(file:///var/folders/wf/94b1wttd0v1b6t0md1pkllp80000gn/T/anonymous2009414429332203653webdriver-profile/extensions/[email protected]/components/command-processor.js:9979)
at <anonymous class>.DelayedCommand.prototype.checkPreconditions_(file:///var/folders/wf/94b1wttd0v1b6t0md1pkllp80000gn/T/anonymous2009414429332203653webdriver-profile/extensions/[email protected]/components/command-processor.js:12517)
at <anonymous class>.DelayedCommand.prototype.executeInternal_/h(file:///var/folders/wf/94b1wttd0v1b6t0md1pkllp80000gn/T/anonymous2009414429332203653webdriver-profile/extensions/[email protected]/components/command-processor.js:12534)
at <anonymous class>.DelayedCommand.prototype.executeInternal_(file:///var/folders/wf/94b1wttd0v1b6t0md1pkllp80000gn/T/anonymous2009414429332203653webdriver-profile/extensions/[email protected]/components/command-processor.js:12539)
at <anonymous class>.DelayedCommand.prototype.execute/<(file:///var/folders/wf/94b1wttd0v1b6t0md1pkllp80000gn/T/anonymous2009414429332203653webdriver-profile/extensions/[email protected]/components/command-processor.js:12481)
* Steps to Reproduce*
Attempts to switch to a modal using the call "driver.switchTo().activeElement();" throws the ClassCast Exception. Code snippet ...:
clickElement(driver, xButton); // which is really a call to driver.findElement(By) wrapped with a WebDriverWait
driver.switchTo().activeElement();
Actual Results
After the call to switch to the modal, we get:
java.lang.ClassCastException: com.google.common.collect.Maps$TransformedEntriesMap cannot be cast to org.openqa.selenium.WebElement
at org.openqa.selenium.remote.RemoteWebDriver$RemoteTargetLocator.activeElement(RemoteWebDriver.java:1045)
at com.automatedTesting.redesigned.pageObjects.NotesModal.closeNotesModal(NotesModal.java:87)
at com.automatedTesting.redesigned.testcases.Notes_testAddAcknowledgeButtonPresence.assertAddAcknowledgeBtnAbsence(Notes_testAddAcknowledgeButtonPresence.java:72)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runners.Suite.runChild(Suite.java:128)
at org.junit.runners.Suite.runChild(Suite.java:27)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
at java.util.concurrent.FutureTask.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
Is it possible to use seleniumQuery with jBrowserDriver?
As per this issue, I can pass an instance of jBrowserDriver to $.driver().use(driver);(since jBD extends WebDriver) but all subsequent calls to $ result in a hang.
Automatic (.exe) driver download! Automatic driver quit! Headless for Chrome and Firefox:
$.driver()
.useChrome()
.headless() // configures chrome to be headless
.autoDriverDownload() // automatically downloads and configures chromedriver.exe
.autoQuitDriver(); // automatically quits the driver when the JVM shuts down
Assertions: Created $().assertThat(). Any function that is available for .waitUntil() is also available for asserting:
Improved waiting: Dramatically improved $().waitUntil() inner-workings and error messages:
$("#foo").waitUntil().size().isGreaterThan(5);
// When failing, it will now show:
//
// Timeout while waiting for $("#foo").waitUntil().size().isGreaterThan(5).
//
// expected: <size() to be greater than 5>
// but: <last size() was 2>
And much more. See below.
Whats new?
Added functions:
$().refresh() - refreshes (requeries) the object, minimizingStaleElementException issues
$.title() - returns page title
$.eval(<javascript code>) - evaluates general JavaScript code
$().eval(<javascript code>) - evaluates general JavaScript code receiving current elements as argument
$().stream() - return a Java 8 Stream
$().map(<function>) - runs the function on every matched element
Created SeleniumQuery.seleniumQueryBrowser() to get the SeleniumQueryBrowser instance used by the global SeleniumQuery.$ field.
Update some dependencies, such as commons-lang3 from 3.5 to 3.6, as well as added commons-text 1.1.
Removed htmlunit's $.driver().useHtmlUnit().emulatingInternetExplorer8(), $.driver().useHtmlUnit().emulatingInternetExplorer11() and other browsers HtmlUnit does not emulate anymore.
Removed $.browser.function()s
The new place for the functions that were in $.browser.FUNCTION is either $.FUNCTION or $.driver().FUNCTION.
In other words, the function $.browser.function() will either be $.function() or $.driver().function().
Removed BrowserFunctionsWithDeprecatedFunctions (class that held that attribute while it was deprecated)
This is the first version released to Maven Central.
Contains most useful jQuery functions, as well as most CSS3 and jQuery/Sizzle extension selectors.
Includes:
The $.driver().use* driver builder system
Several .waitUntil() functions
Initial plugin .as() functions
All integration tests (about 3.5k tests over 2h40m) were be run against HtmlUnit (JS ON and OFF), Chrome, Firefox (JS ON and OFF), PhantomJS and IE 11.
There are minor errors in this current baseline, but the merge of the XPath system is really needed right now, so I'm creating this tag right now in order to mark a rollback point if ever needed.
Most useful jQuery functions sizzle/jQuery selectors are supported.
Next steps are:
Remove old .waitUntil() code to simplify the function stack call (so debugging is clearer);
Possibly rework CSS selector system into a CSS to XPath compiler, as some selectors (such as :contains() when used alone demand too much work and can be slow).
This is an EFX translator written in Java. It supports multiple target languages. It includes an EFX expression translator to XPath. It is used to in the generation of the Schematron rules in the eForms SDK.