Selenium Webdriver Coding Tips

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 12

SELENIUM WEBDRIVER CODING TIPS FOR SOFTWARE TESTERS.

With these Selenium Webdriver coding tips, weve tried to cover various use cases
that you face in real-time. We expect you to use these coding snippets directly in
your current project assignments. BTW if you fall into any issues while using these
tips, then do write to us. Well try to respond to each and every query of our readers.

TIP-1: BEST METHOD TO CREATE WEBDRIVER INSTANCE.

Its one of the most common Selenium Webdriver coding tips which you cant avoid
to use.
1.1- Use the <Factory> design pattern to create objects based on browser type.
1.2- Extend the below code or use it as is in your projects.

Java

1
2
3
4
5
6
7
8
9 public class DriverFactory {
1
private WebDriver driver = null;
0
1
public static WebDriver getBrowser(String browserType) {
1
if (driver == null) {
1
if (browserType.equals("Firefox"))
2
1
{
3
driver = new FirefoxDriver();
1
4
} else if (browserType.equals("Chrome"))
1
5
{
1
driver = new ChromeDriver();
6
1
} else if (browserType.equals("IE"))
7
1
{
8
driver = new InternetExplorerDriver();
1
9
}
2
}
0
return driver;
2
}
1 }
2
2
2
3
2
4
2
5

TIP-2: SIMPLE METHOD TO CHECK IF AN ELEMENT EXISTS.

2.1- You should use <findElements> instead of <findElement>.


2.2- <findElements> returns an empty list when it doesnt find any matching
elements.
2.3- You can use the code given below to check for the presence of an element.

Java

1 Boolean isItemPresent = driver.findElements(By.testLocator).size() > 0

TIP-3: AVOID EXCEPTION WHILE CHECKING AN ELEMENT EXISTS.

3.1- The code in the previous tip may lead to <NoSuchElementException>. Also, it
could be a bit slower in some cases.
3.2- Webdriver has a Fluent wait feature. We can use it to check the element.
3.3- It gives the ability to ignore any exception and allows to test
the <WebElement>. Lets see how to achieve whats said here.

Java
1
2
3
4
5
6
7
8
9
1
0

/* 1- Test if an element exists on the page.


2- Ignore the no element found exception.
*/
By element = By.xpath(".//*[@id='demo']/p");
Wait < WebDriver > wait = new FluentWait < > (driver)
.withTimeout(60, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
wait.until(ExpectedConditions
.presenceOfElementLocated(element));

TIP-4: WAIT FOR A PAGE WITH JAVASCRIPT(JS) TO LOAD.


4.1- Its quite common working with pages bloated with JavaScript. The challenge is
how to make sure the page has finished loading.
4.2- Here, we are giving a solution that works. This code will help you setting wait for
a page containing JavaScript.

Java
wait.until(new Predicate < WebDriver > () {
1
@Override
2
public Boolean apply(WebDriver driver) {
3
return ((JavascriptExecutor) driver).executeScript("return
4
document.readyState").equals("complete");
5
}
6
});

TIP-5: TAKE A SCREENSHOT USING WEBDRIVER.


5.1- Its easy to capture a screenshot of any error using Webdriver.
5.2- Use the below Webdriver code. It saves the screenshot to the current project
directory.

Java
1
2
3
4
5
6
7
8
9
1
0
1
1

WebDriver driver = new FirefoxDriver();


driver.get("http://www.techBeamers.com/");
// Store the screenshot in current project dir.
String screenShot = System.getProperty("user.dir") + "\\screenShot.png";
// Call Webdriver to click the screenshot.
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
// Save the screenshot.
FileUtils.copyFile(scrFile, new File(screenShot));

TIP-6: TAKE A PARTIAL SCREENSHOT USING SELENIUM


WEBDRIVER.
Its one of the premium Selenium Webdriver coding tips.

6.1- Sometimes you only need to take a screenshot of the part of the screen. Like of
only one frame within a set of frames.
6.2- You can add below code in your project to shot the image of a particular frame.
6.3- Find the <WebElement> of the frame and pass it to the function given below.

Java
1
2
3
4
5
6
public void takePartialScreenShot(WebElement element) throws IOException {
7
8
String screenShot = System.getProperty("user.dir") + "\\screenShot.png";
9
1
File screen = ((TakesScreenshot) this.driver).getScreenshotAs(OutputType.FILE);
0
1
Point p = element.getLocation();
1
1
int width = element.getSize().getWidth();
2
int height = element.getSize().getHeight();
1
3
BufferedImage img = ImageIO.read(screen);
1
4
BufferedImage dest = img.getSubimage(p.getX(), p.getY(), width,
1
height);
5
1
ImageIO.write(dest, "png", screen);
6
1
FileUtils.copyFile(screen, new File(screenShot));
7
}
1
8
1
9
2
0

6.4- You may require adding a few imports to get the above code working.

Java

1 import
2 import
3 import
4 import

org.openqa.selenium.Point;
org.openqa.selenium.TakesScreenshot;
java.awt.image.BufferedImage;
javax.imageio.ImageIO;

6.5- Alternatively, you can use the <CTRL+SHIFT+O> shortcut in Eclipse.

TIP-7: GET HTML SOURCE OF WEBELEMENT IN SELENIUM


WEBDRIVER.

7.1- Webdrivers <WebElement> class provides <getAttribute()> method to get the


HTML inside the element.
7.2- You need to pass the <innerHTML> as attribute type in the above method. See
the code below.

Java

1 String html = element.getAttribute("innerHTML");

TIP-8: HOW TO SELECT/GET DROP DOWN OPTION IN SELENIUM


WEBDRIVER.
You can achieve this in the following two steps.

8.1- Select an option based on the label.

Java

1 Select dropdown = new Select(driver.findElement(By.xpath("//drop_down_x_path")));


2 dropdown.deselectAll();
3 dropdown.selectByVisibleText("selectLabel");

8.2- Get the first selected value from the dropdown.

Java
1 WebElement option = dropdown.getFirstSelectedOption();

TIP-9: REFRESHING WEB PAGE BY WEBDRIVER DURING TESTS.


9.1- The below code should refresh the web page.

Java

1 driver.navigate().refresh();

TIP-10: RUN A JAVASCRIPT CODE USING SELENIUM WEBDRIVER.

10.1- When you are testing a website, you cant skip using JavaScript.
10.2- Webdriver provides support to call JavaScript.
10.3- You just need to add the below lines in your project.

Java
1 JavascriptExecutor JS = (JavascriptExecutor) driver;
2 JS.executeScript("alert('hello world')");

TIP-11: GETTING THE RESULT OF JAVASCRIPT CODE IN


WEBDRIVER.

11.1- Its a bit tricky but easy. Use the <return> keyword in JavaScript to send back
the result.
11.2- Place the following code in your project.

Java
1 ((JavascriptExecutor) driver).executeScript("return 10");

TIP-12: PERFORM MOUSEOVER FUNCTION USING WEBDRIVER IN


JAVA.
12.112.312.512.4-

Java

Sometimes you need to use a mouseover function with a drop down menu.
When you hover over the menu, it shows new options.
Webdriver provides an <Actions> class to handle mouse events.
We can achieve this by chaining all actions to simulate mouse hover.

Actions action = new Actions(driver);


1
WebElement item = driver.findElement(By.xpath("html/body/div[5]/ul/li[5]/a"));
2
action.moveToElement(item).moveToElement(driver.findElement(By.xpath("/write-expression3
here"))).click().build().perform();

TIP-13: MAKE SELENIUM WEBDRIVER CLICK A CHECKBOX WHICH


IS NOT CURRENTLY VISIBLE.
13.1- Sometimes youve to click checkboxes on a form. But you fall into problems
when they get added dynamically.
13.2- If you use Webdriver calls, following error occurs.

Java

1 "Element is not currently visible and so may not be interacted with."

13.3- In such cases, we advise to use Webdrivers JavaScript executor to do the job.
13.4- Check out the below lines of code.

Java
1 ((JavascriptExecutor)driver).executeScript("arguments[0].checked = true;", checkbox);

TIP-14: SWITCH TO A NEW BROWSER WINDOW IN WEBDRIVER.


14.1- You can easily switch between popup windows.
14.2- Copy the below code in your project to switch windows.

Java
1
2
3
4
5
6
7
8
9
1
0
1
1
1
2
1
3
1
4
1
5
1
6
1
7

// Get the current window handle.


String hBefore = driver.getWindowHandle();
// Click to open new windows.
// Switch to new windows.
for(String hNew: driver.getWindowHandles()){
driver.switchTo().window(hNew);
}
// Close all new windows.
driver.close();
// Switch back to first window.
driver.switchTo().window(hBefore);
// Resume your work.

TIP-15: SETTING DRIVER EXECUTABLE PATH IN WEBDRIVER.


15.1- For some browsers, Webdriver needs to know the locations of their driver
files. e.g. Chrome, and IE.
15.2- We need to set the driver file path in the Webdriver configuration.
15.3- See the code snippet given below. We took IE as an example.

Java
1 File ieDriver = new File("path/to/iexploredriver.exe");
2 System.setProperty("webdriver.ie.driver", ieDriver.getAbsolutePath());
3 WebDriver driver = new InternetExplorerDriver();

TIP-16: FIND ELEMENT USING CSS IN WEBDRIVER.


16.1- While working with list items, you may find it interesting to use CSS for locating
elements. Lets learn in depth with the help of examples.
16.2- Use case: Youve to find the third element from a list. The element is an anchor
text and uses <css1> and <css2> classes for styling.
16.3- Implement with <By.CssSelector>.

Java

1 IList<IWebElement> list = driver.FindElements(By.CssSelector(".css1.css2"));


2 IWebElement target = list[3];

16.4- Implement with <By.XPath>.

Java

1 driver.FindElement(By.XPath("(//a[contains(@class, 'css1 css2')])[3]"));

TIP-17: OPEN A NEW TAB USING SELENIUM WEBDRIVER IN JAVA.

17.1- At times you may need to open a new tab in the same browser window. Its
easy to do it, use the following code.

Java

1 driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

17.2- If you wish to run your tests in the new tab, then youve to switch to it first.
Check out the given code fragment.

Java

1 ArrayList<String> tablist = new ArrayList<String> (driver.getWindowHandles());


2
3 driver.switchTo().window(tablist.get(0));

Now lets here some of the premium Selenium Webdriver coding tips that weve
already published on our blog.

TIP-18: HANDLE AJAX CALLS IN SELENIUM WEBDRIVER.


18.1- Read the below post to see 6 unique ways to handle Ajax calls.
6 WAYS TO HANDLE AJAX CALLS.

AJAX is an advance communication technique used by Web applications to exchange


the data from the server without affecting the state of the currently opened web
page. It saves the reloading of the page on the client-side and cuts down the number
of requests on the server making it respond faster. Because of these apparent
advantages, many websites use AJAX calls to improve their user experience. But
using the AJAX controls poses a challenge for the Selenium Webdriver as it gets only
a fraction of seconds to act on the changes made by the AJAX calls. Hence, in this
blog post, well share some of the best techniques to handle AJAX calls in Selenium
Webdriver. If you wish to know more about the AJAX tests, then please read
from here. Youll get to learn the following topics from this article.
What is AJAX and how does it work?
How to Handle AJAX calls using Selenium Webdriver?
Sample Code for Handling AJAX calls in Selenium Webdriver.

WHAT IS AJAX AND HOW DOES IT WORK?

AJAX is a popular acronym for Asynchronous JavaScript and XML which many
people confuse as a programming language. But its a technology that works with
the combination of JS, CSS and, XML. It enables a web page to request the limited
amount of information from the server without the need of refreshing the whole
page.
You can consider an example when a user submits a form, the JavaScript dispatches
the request to the server, process the response and update a part of the screen
without refreshing the browser.

How Ajax Call Communicates with the Web Server.


Some of the points which can be helpful in the testing of AJAX applications are as
follows.
When a browser makes an AJAX call, it may not result in a page navigation. So you
need to be careful what part of the page is getting changed by the server response.
AJAX calls are asynchronous and dont block the execution. So, the user can still use
the application till the server process his request. For a tester, it would mean that he
cant estimate the actual time the server would take to deliver the response.

HOW TO HANDLE AJAX CALLS USING SELENIUM


WEBDRIVER?
You would now have an idea of the hurdles that a tester could face while
automating a web page that makes AJAX calls. The main issue is how to handle the
AJAX call when you are not sure of the loading time of the webpage. Sometimes the
change would be so sudden that it would disappear in a flash. In this situation,
youve to devise a strategy which should be dynamic and perceptive.
So, lets discuss the options that we can deploy to handle AJAX calls in Selenium
webdriver.
1- USING <THREAD.SLEEP(TIME IN MS)> FOR HANDLING AJAX CONTROLS.
<Thread.sleep()> is an obvious choice for handling AJAX calls. But it may not give
you the best result. Instead, a test could break intermittently if the server response
time exceeds the time specified in sleep. Additionally, the test has to wait for the
given time even in a situation of the timely response. Though keeping all the odds
aside, this method does work, and weve tested it as working.

2- USING JAVASCRIPT TO HANDLE AJAX CALLS IN SELENIUM WEBDRIVER.


This method is only useful if the web application has jQuery in use to handle AJAX
calls. Since jQuery uses a mechanism which keeps the no. of active AJAX calls in
check, we can utilize this information to find out their final status.
Here is a sample code to showcase the handling of AJAX controls using Selenium
Webdriver. You can integrate it in your test execution class.
Use JavaScript to Handle AJAX Calls in Selenium Webdriver.
public void waitForAjaxControls(int timeoutInSeconds) {
System.out.println("Querying active AJAX controls by calling jquery.active");
try {
if (browser instanceof JavascriptExecutor) {
JavascriptExecutor jsDriver = (JavascriptExecutor) browser;
for (int i = 0; i < timeoutInSeconds; i++) {
Object numberOfAjaxConnections = jsDriver
.executeScript("return jQuery.active");
// return should be a number

if (numberOfAjaxConnections instanceof Long) {


Long n = (Long) numberOfAjaxConnections;
System.out.println("Number of active jquery AJAX controls: "
+ n);
if (n.longValue() == 0L)
break;
}
Thread.sleep(1000);
}
} else {
System.out.println("Web driver: " + browser
+ " can't run javascript.");
}
} catch (InterruptedException e) {
System.out.println(e);
}
}

3- HOW TO USE IMPLICIT WAIT TO HANDLE AJAX CALLS IN SELENIUM WEBDRIVER.


An implicit wait is a Webdriver mechanism to query the DOM for a specified time
duration to locate an element or a set of elements till they become available.
The default timeout value is 0.
Once you define it, the implicit wait is available for the lifetime of the Webdriver
instance.
Define Implicit wait for handling of AJAX calls.
1 WebDriver browser = new FirefoxDriver();
2 browser.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
3 browser.get("http://www.techbeamers.com/");
4 WebElement ajaxControl = browser.findElement(By.id("DummyElement"));

4- HOW TO USE WEBDRIVER EXPLICIT WAIT FOR HANDLING AJAX CONTROLS.


It is yet another Webdrivers built-in feature to handle AJAX calls. Just like the
<Thread.sleep()>, you can get it working when no other tricks other work.
Use of An Explicit Wait to Handle AJAX Controls.
1 WebDriver browser = new FirefoxDriver();
2 browser.get("http://www.techbeamers.com/");
3 WebElement ajaxControl = (new WebDriverWait(browser, 15))
4
.until(ExpectedConditions.presenceOfElementLocated(By
5
.id("DummyElement")));

5- USING WEBDRIVER FLUENT WAIT TO HANDLE AJAX CALLS.


Its an implementation of the Webdrivers Wait interface which brings both the
timeout and polling interval to use. The Fluent wait makes use of the timeout to wait
for a condition, also the frequency for the no. of attempts.
Its example you can see in the last section where weve demonstrated the combined
use of <FluentWait> and the <WebdriverWait>.
6- USING <WEBDRIVERWAIT> FOR HANDLING THE AJAX CALLS.
It is one of the best Webdriver strategies to handle the AJAX controls. It allows you
to implant a condition to check at regular intervals and break to next step as soon as
the condition get fulfilled.
Apart from the <WebdriverWait>, we also use the <ExpectedCondition> to get
the entire mechanism in place. Weve covered the detailed example in the next
section.

SAMPLE CODE FOR HANDLING AJAX CALLS IN SELENIUM


WEBDRIVER.

So far, youve seen six different strategies to work with the AJAX controls using
Selenium Webdriver. In most of these methods, weve used various types of waits to
handle the AJAX calls.
Thread.sleep()
Implicit Wait
Explicit Wait
Fluent Wait
WebdriverWait
Now, well give you a fully working demo of using the <FluentWait> and
<WebdriverWait> for handling the AJAX controls.
Weve used a w3schools.coms demo website for testing the automation of AJAX
calls.
AJAX CALL TEST CASE SCENARIO.
DEMO SITE USED:
Weve used the following demo URL for our testing which is using the AJAX calls.
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_callback
TEST CASE DESCRIPTION:
Open the demo AJAX application demo website.
Following AJAX controls would appear in an IFRAME.
A demo paragraph element which contains some default text.
A simple button control to make the AJAX calls.
When you click the button control, the AJAX call takes place.
The default text disappears from the screen.
Two new paragraphs get displayed on the screen.
You now need to validate the two conditions.
The new text in the first paragraph shouldnt match the default text.
The text in the second paragraph should match the expected value.
Note: Well read the default text from the demo paragraph as it would appear first
on the screen. For the second paragraph, weve hard wired the value in the sample
code which we copied from the demo test site.
Now, youll see the sample source code below. It should be self-explanatory as weve
added comments for each step.
Sample Code for Handling AJAX calls in Selenium Webdriver.
import java.util.concurrent.TimeUnit;
import
import
import
import
import
import
import
import
import
import
import
import
import
import

org.openqa.selenium.By;
org.openqa.selenium.JavascriptExecutor;
org.openqa.selenium.NoSuchElementException;
org.openqa.selenium.WebDriver;
org.openqa.selenium.WebElement;
org.openqa.selenium.firefox.FirefoxDriver;
org.openqa.selenium.support.ui.ExpectedConditions;
org.openqa.selenium.support.ui.FluentWait;
org.openqa.selenium.support.ui.Wait;
org.openqa.selenium.support.ui.WebDriverWait;
org.testng.Assert;
org.testng.annotations.AfterTest;
org.testng.annotations.BeforeTest;
org.testng.annotations.Test;

public class AjaxTesting {


private String ajaxTestSite = "http://www.w3schools.com/ajax/tryit.asp?
filename=tryajax_callback";
WebDriver browser;
WebDriverWait wait;
@BeforeTest

public void startTest() {


// Launch the demo web page to handle AJAX calls using Webdriver.
browser = new FirefoxDriver();
browser.manage().window().maximize();
browser.navigate().to(ajaxTestSite);
}
@Test
public void test_AjaxCalls() {
/* Wait for the AJAX controls to appear. */
browser.switchTo().frame(browser.findElement(By.id("iframeResult")));
By container = By.xpath(".//*[@id='demo']");
wait = new WebDriverWait(browser, 5);
wait.until(ExpectedConditions.presenceOfElementLocated(container));
/* Read the text that appears in the AJAX text control. */
WebElement ajaxControl = browser.findElement(container);
String ajaxTextFirstPara = ajaxControl.getText().trim();
/* Click on the AJAX button control. */
browser.findElement(By.xpath("html/body/button")).click();
/* Wait for the new content to appear in the AJAX text control. */
By newAjaxcontrol = By.xpath(".//*[@id='demo']/p");
Wait<WebDriver> newwait = new FluentWait<>(browser)
.withTimeout(60, TimeUnit.SECONDS)
.pollingEvery(5, TimeUnit.SECONDS)
.ignoring(NoSuchElementException.class);
newwait.until(ExpectedConditions
.presenceOfElementLocated(newAjaxcontrol));
/*
* Wait for the second paragraph value to get visible in the AJAX text
* control.
*/
WebElement secondParagraph = browser.findElement(By
.xpath(".//*[@id='demo']/p[2]"));
wait.until(ExpectedConditions.visibilityOf(secondParagraph));
/* Get the text from the first paragraph after the AJAX call. */
String ajaxNewTextFirstPara = browser
.findElement(By.xpath(".//*[@id='demo']/p[1]")).getText()
.trim();
/* Get the text from the second paragraph after the AJAX call. */
String ajaxTextSecondPara = secondParagraph.getText().trim();
String expectedTextInSecondPara = "AJAX is a technique for creating fast and dynamic
web pages.";
/* Verify the first paragraph text shouldn't match the new text. */
Assert.assertNotEquals(ajaxTextFirstPara, ajaxNewTextFirstPara);
/* Verify the second paragraph text must match with the new text. */
Assert.assertEquals(ajaxTextSecondPara, expectedTextInSecondPara);
}
@AfterTest
public void endTest() {
browser.quit();
}
}

If you wish to test the sample program then, add the above Java code to a TestNG
project in Eclipse. Whenever youll run this program, itll execute successfully and
produce the following report.

Test Summary Handle AJAX Calls Using Selenium Webdriver.


If you are reading this post and would like to appreciate our work or ask questions
then, you are most welcome to share. If you knew an alternative technique for
handling the AJAX calls then, we would love to hear it from you.
Please use the comment box and send us your views.

TIP-19: SCHEDULING SELENIUM WEBDRIVER TESTS IN WINDOWS


7.
19.1- Read the below post to setup Selenium Webdriver testing using Windows task
scheduler.
SELENIUM WEBDRIVER IN WINDOWS 7.

1- PREPARE A WINDOWS BATCH FILE TO RUN SELENIUM TESTS.


There could be three use cases which you may need to handle.
1.1- You have the Selenium tests in a single or multiple class files.
Use the below command to run the tests. Keep the Selenium library on the current
path. And name Java class file as<SeleniumTests.java>.
1 java -classpath .;selenium-server-standalone-2.53.0.jar SeleniumTests

1.2- You have the Selenium tests exported from Eclipse as a Runnable Jar
file.
Use the below command to run the tests. Make sure the output Jar contains all the
Selenium dependencies.
1 java -jar SeleniumTests.jar

1.3- You might be using <testng.xml> to run Selenium tests.


Use the below command to run the tests.
1 java -cp "path/to/testng.jar:path/to/testClass" org.testng.TestNG testng.xml

You can check more details from here to run testng.xml from the command line.
1.4- Now, use the below code to add into a batch file. Save the batch file
as <run.bat>.
set MyProject=C:\tests\SeleniumTests
echo %MyProject%
set classpath=%MyProject%\bin;%MyProject%\Lib\*
echo %classpath%
java org.testng.TestNG %MyProject%\testng.xml

2- HOW TO RUN A BATCH FILE USING THE TASK SCHEDULER IN WINDOWS 7?


2.1- Open control panel.
2.2- Go to <Administrative tool >>Task scheduler>.
2.3- Create a task to run the batch file. Also, specify the time to start the execution.

2.4- Dont forget to check the below setting in task scheduler.


1 "Run only when user is logged on"

Read from this link for more detail on task scheduler.


If you have any query about the above steps, then do leave it in the comment box.
Well try to address at the earliest possible.

TIP-20: SCHEDULING SELENIUM WEBDRIVER TESTS IN LINUX.


20.1- Read the below post to run Selenium Webdriver tests using crontab in Linux.
SELENIUM WEBDRIVER IN LINUX.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy