Custom locator in WebDriver for Jquery

66 views
Skip to first unread message

Amit singh

unread,
Nov 19, 2016, 8:55:43 PM11/19/16
to webdriver
Can anyone please let me know if we can extend locator functionality using Jquery like 
driver.findElement(By.Jquery("Jquery string"));


-Amit

darrell grainger

unread,
Nov 20, 2016, 5:45:43 PM11/20/16
to webdriver
if you can open up Inspect in Chrome or Firebug in Firefox, go to the Console and enter:

document.querySelectorAll("your selector here")

then replace "your selector here" with a selector that works (finds one and only one element) then you can use that selector in WebDriver using:

driver.findElement(By.cssSelector("your selector here"));

I haven't tried jquery selectors but you might be able to use them just like CSS selectors. Give it a try and see if that works. 

Darrell

David

unread,
Nov 21, 2016, 3:58:52 PM11/21/16
to webdriver
Darrell,

Amit was kind of asking about creating a By.JQuery() class in Java to find locators, not exactly what you are talking about.

But while on this related subject, without creating By.JQuery() or similar, you can use jQuery locators in any WebDriver language binding like this (Java example given), assuming jQuery is imported/loaded or available in your website/application being tested (i.e. WebDriver doesn't have native jQuery support if it's not loaded in the website/application):

String jQuerySelectorValue = "your jquery selector value here"; //e.g. "$(#someId)"
WebElement elem = (WebElement) ((JavascriptExecutor) driver).executeScript("return arguments[0];", jQuerySelectorValue);
//now do whatever you do with elem like a normal WebElement you've found


darrell grainger

unread,
Nov 22, 2016, 3:21:37 PM11/22/16
to webdriver
I was suggesting that maybe the JQuery selectors Amit was wanting to use might actually be supported by CSS 3.0 and could use the By.ccsSelector(). I believe there are some JQuery selectors which aren't CSS 3.0, e.g. ":text", and I don't know if they'll work. But if they will work with CSS 3.0 then you can use the By.ccsSelector() method.

I like the idea of using executeScript for this but I've never been able to make it work. For example, if I go to a site which uses JQuery and set the jQuerySelectorValue to say "$(':text#uniqueID');" then I get the error:

java.lang.ClassCastException: java.lang.String cannot be cast to org.openqa.selenium.WebElement

If I cast the result to (String) and print it, it prints "$(':text#uniqueID');". Shouldn't something like the following work:

driver.get("http://api.jquery.com/");
String jquerySelector = "$(':text');";
WebElement textInput = (WebElement) ((JavascriptExecutor)driver).executeScript("return arguments[0];", jquerySelector);

Darrell

David

unread,
Nov 23, 2016, 12:19:39 PM11/23/16
to webdriver
Ah, I've never done that myself Darrell, but assumed it would work in theory. Good to know.
Reply all
Reply to author
Forward
0 new messages