Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting and Identifying element with JQuery to use it in Selenium 2 Java API

This is the situation:

  • I use the Java API of Selenium 2 to open and control a firefox browser instance
  • I load the jQuery script to a page via JavaScript execution
  • I then use jQuery expressions to select elements and traverse through the DOM tree

Now is my question, can i somehow find a unique identifier for each of the found elements? My goal is to get the same element with Selenium by using an Xpath or CSS selector. So it would be most straighforward if i could generate an unambiguous selector for the elements in jQuery. Other ideas are welcome too.

I need an automatic approach for identifying elements in jQuery, which can be "converted" to Selenium elements / locators.

/edit

To make it clearer:

If i have selected an element in jQuery:

webDriver.executeScript("var element = $('#myDiv input.test')");

Now, I want something like this:

WebElement webElement = webDriver.executeScript("return element");

Is that possible?

like image 422
Alp Avatar asked Mar 30 '11 18:03

Alp


People also ask

Can we use jQuery in Selenium?

Selenium WebDriver can be enhanced by jQuery selectors using the jQuery API. However, we need to make sure that the page has jQuery API loaded before using these selectors. The jQuery API provides the find() function through which we can search for elements.

How do I select an element by ID in Selenium?

Go to the First name tab and right click >> Inspect. On inspecting the web element, it will show an input tag and attributes like class and id. Use the id and these attributes to construct XPath which, in turn, will locate the first name field.

What methods can we use to click the elements apart from .click method?

Alternative of click() in Selenium We can use the JavaScript Executor to perform a click action. Selenium can execute JavaScript commands with the help of the executeScript method. The parameters – arguments[0]. click() and locator of the element on which the click is to be performed are passed to this method.


1 Answers

I found the solution, which is quite easy:

String jQuerySelector = "'#myDiv input.test'";
RenderedWebElement webElement = (RenderedWebElement) ((JavascriptExecutor) webDriver).executeScript("return $(" + jQuerySelector+ ").get(0);");

Working with an element in jQuery which was previosly selected in Selenium works too:

String jQuerySelector = "arguments[0]";
((JavascriptExecutor) webDriver).executeScript("return $(" + jQuerySelector+ ").doSomethingInJquery();", webElement);
like image 155
Alp Avatar answered Sep 20 '22 03:09

Alp