Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use JQuery in Selenium?

I would like to use Selenium to click on the tab of a web where the tab was created dynamically using JQuery. There is one problem, since it was created dynamically and the tab got no ID tied to it (only class-ID provided), so I am running out of clue to click on it using Selenium.

After googling for 2 weeks, I found out that it could be done using JQuery by injecting JQuery into Selenium and repackaging it so that it support JQuery API. But the problem now is I don't know how to trigger JQuery script in Selenium?

Is there any resources out there or guideline on setting up JQuery in Selenium? How am I going to execute JQuery in Selenium?

like image 231
huahsin68 Avatar asked Jul 13 '10 07:07

huahsin68


People also ask

What is the use of jQuery in selenium?

The known javascript library, called jQuery, provides a bunch of methods that can be performed over any web element and, of course, since Selenium is able to run javascript code, you can run jQuery methods on them using WebDriver.

Can I use JavaScript with selenium?

Selenium is an open-source automation testing tool that supports a number of scripting languages like C#, Java, Perl, Ruby, JavaScript, etc.

Can you use jQuery in JavaScript?

jQuery code is implemented as part of JavaScript scripts. To add jQuery and JavaScript to your web pages, first add a <script> tag that loads the jQuery library, and then add your own <script> tags with your custom code.


2 Answers

You can try using my selenium lib at github.

It handles almost the entire jquery API minus the functions that use/require handler passing:

HtmlUnitDriver drv = new HtmlUnitDriver(BrowserVersion.FIREFOX_3_6);
drv.setJavascriptEnabled(true);
try {
  jQueryFactory jq = new jQueryFactory();
  jq.setJs(drv);

  drv.get("http://google.com");
  jq.query("[name=q]").val("SeleniumJQuery").parents("form:first").submit();

  String results = jq.queryUntil("#resultStats:contains(results)").text();
  System.out.println(results.split(" ")[1] + " results found!");
} finally {
  drv.close();
}
like image 116
Nthalk Avatar answered Sep 22 '22 08:09

Nthalk


Since you said that you didn't have an ID but a class:

(only class-ID provided)

...a better answer is likely to use the CSS locator strategy which is already baked-in to Selenium where you can select an element based on a css class or simply by using CSS selector logic (for at least css2 and css3)

So to select an element (div, span whatever) that has a specific class you can simply use this for the Selenium locator:

css=.class-ID

You can even use more complicated selectors that are similar to those available in JQuery such as:

css=#myDiv .class-ID

This will search for the element with a css style of class-ID within the element with an ID = myDiv.

like image 35
Jay Stevens Avatar answered Sep 18 '22 08:09

Jay Stevens