Selenium Webdriver Coding Tips
Selenium Webdriver Coding Tips
Selenium Webdriver Coding Tips
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.
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
Java
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
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
});
Java
1
2
3
4
5
6
7
8
9
1
0
1
1
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;
Java
Java
Java
1 WebElement option = dropdown.getFirstSelectedOption();
Java
1 driver.navigate().refresh();
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')");
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");
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.
Java
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);
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
Java
1 File ieDriver = new File("path/to/iexploredriver.exe");
2 System.setProperty("webdriver.ie.driver", ieDriver.getAbsolutePath());
3 WebDriver driver = new InternetExplorerDriver();
Java
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
Now lets here some of the premium Selenium Webdriver coding tips that weve
already published on our blog.
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.
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;
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.
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
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