Saturday, January 25, 2014

How to execute JavaScript using Selenium WebDriver


With Java Script we can access the DOM Properties. By doing so we can get the properties values of those objects.

Say i have a Div or a Span control like below:
<Div id="SampleDiv1">I am in Div</Div> or
<Span id="SampleSpan1">I am in Span</Div>

Here we have two solutions to get the value of the objects.

Solution 1: Use the getAttribute method.
This method is described in below location:
http://selenium.googlecode.com/svn/trunk/docs/api/java/org/openqa/selenium/WebElement.html#getAttribute%28java.lang.String%29

So for ex above, we can use like:
String sReturnText=driver.findElement(By.id("SampleSpan1")).getAttribute("innerHTML");
System.out.println(sReturnText);


Because in the above example we are trying to get text from the control we can directly use getText method like below:
String sReturnText=driver.findElement(By.id("SampleSpan1")).getText();
System.out.println(sReturnText);

Solution 2: We can get the DOM properties be JavaScript
There might be situations you will be needing to run the JavaScript in your automation. To do this/cover the example follow below steps:
String sJScript = "return document.getElementById('SampleSpan1').innerHTML;";
String sReturnText = (String) ((JavascriptExecutor) driver).executeScript(sJScript);
 System.out.println(sReturnText);

No comments:

Post a Comment