{{announcement.body}}
{{announcement.title}}

Selenium Scripting Tips and Tricks

DZone 's Guide to

Selenium Scripting Tips and Tricks

For those just starting out with using Selenium WebDriver, this list of tricks, tips, and useful commands should be helpful.

· DevOps Zone ·
Free Resource

If you are just started to learn Selenium then the below tricks and tips will be helpful. These tips and tricks have all the basic things element of using Selenium that you might forget and it will help you in remembering them. Let’s have a look at all the tricks and tips one by one.

Image title

Create a Web Driver Instance

You can make your tests generic. The first step will be initializing the browser by passing the value from the configuration file. You can have one key as the browser and the value as Chrome, Firefox or IE. You can then initialize the browser according to the value passed there. Let’s look at the code which will be involved.

public static WebDriver getBrowser(String browserName)
{
If(driver == null)
{ 
if(browserName.equals(“firefox”))
{
driver = new FirefoxDriver();
}
else if(browserName.equals(“Chrome”))
{
driver=new ChromeDriver();
}
else if(browserName.contains(“IE”))
{
driver=new InternetExplorerDriver();
}
}
return driver;
}


Check Whether an Element Exists or Not

If you have to check whether an element exists in the web application or not, you can easily do it by getting the size of the web element and then checking if it is greater than zero or not.

Boolean isElementExists = driver.findElements(By.xpath(“”)).size()>0 

How to Wait for Page to Load Completely

Sometimes, you have to wait for a page is to load completely. For this, you have to first check whether it is loaded properly and then you can do any other operation on it. You can use the Javascript executor to check whether the page is loaded completely or not.

wait.until(new Predicate < WebDriver > () {
    @Override
    public Boolean waitPageLoaded(WebDriver driver) {
        return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
    }
});


How to Take a Screenshot Using Selenium WebDriver

Sometimes, it is very important to take screenshots while execution to know what went wrong. You can have Selenium Driver and then you can cast it to takes Screenshot interface. Make an instance of it and then use it to get the screenshot. You can use kits method .getScreenshotAs and then you can specify in which format you are expecting your screenshots to be.

// Storing the screenshot in current project directory
String screenShot = System.getProperty("user.dir") + "\\screenshottest.png";

//casting Webdriver to take the screenshot
File srcFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);

// Saving the screenshot
FileUtils.copyFile(srcFile, new File(screenShot));


Get the HTML Source of a Web Element 

Selenium WebDriver provides you a method called getAttribute which will allow you to get the inner HTML of a web element. You can do it by getting the element first. Afterwards, you can use getAttribute to get the innerHTML of a web element.

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


How to Select Dropdown Options Using the Select Class

In Selenium, if you encounter a dropdown then you can select any option in it using the Select class. There are many ways by which you can select an option, which includes selecting by text, index, or values.

Select drp= new Select(Driver.findElement(By.xpath(“”));
drp.deselectAll();
drp.selectByVisibleText("selectLabel");


Refresh a Web Page in WebDriver

If you want to refresh the page then you can use navigate() method, then use refresh() method to actually refresh the page so that all elements will be initialized from the beginning.

driver.navigate().refresh();


How to Switch to A New Tab

The first thing to do is to use .getWindowHandles() and then you can switch to the first index of the array list with all the window handles.

ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));


Set the Driver Executable Path

For browsers, you have to see the path for the driver executables. For setting the path you have to use the System.setProperty method in Selenium. Let’s see how it looks.

File ieDriverPath = new File("path//iexploredriver.exe");
System.setProperty("webdriver.ie.driver", ieDriverPath.getAbsolutePath());
WebDriver driver = new InternetExplorerDriver(); 


Switch to A New Popup Window

If you want to switch to a specific window which is opened then you can first use getAllWindowHandles()  and then switch using the method  driver.switchTo() .

// Get the current window handle.
String hBefore = driver.getWindowHandle();

// action which opens lot of 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);


But if you want to specifically switch to a particular window, you can get a web element and see the visibility of it in a particular window. If it is present, then you can switch to it.

// Get the current window handle.
String hBefore = driver.getWindowHandle();

// Click to open new windows.

// Switch to window which has a webelement attached to it
for(String hNew: driver.getWindowHandles()){
If(driver.findElements(By.xpath(“”)).size()>0)
{
    driver.switchTo().window(hNew);
}
}

// Close all new windows.
driver.close();

// Switch back to first window.
driver.switchTo().window(hBefore);


How to Click on A Checkbox Which Isn’t Visible

There are many instances when the checkbox you want to click isn’t visible and unfortunately you won’t be able to click on it. You have to first enable it so that you can actually click on it. If you don’t enable it then you will get exception like, “Element is not currently visible and so may not be interacted with."

JavaScript executor can be used to enable it so that Selenium can click on it. The code snippet is below:

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


How to Do a Mouseover Action

If you want to mouse over a web element, you can use the Actions() class to handle it. You can use function moveToElemenet() and then build() and perform() in a sequence to perform mouse hovering action on a web element.

Actions action = new Actions(driver);
WebElement item = driver.findElement(By.xpath(""));
action.moveToElement(item).moveToElement(driver.findElement(By.xpath(""))).click().build().perform();


Delete Cookies Before Running a Test Script

Sometimes it is very important to clear all the cookies before running your test scripts. You can use method DeleteAllCookiesfunction of  driver.manage() .

The code snippet is as below:

 this.driver.Manage().Cookies.DeleteAllCookies(); 

Also, if you have a cookie with a particular name, then you can delete it using the method DeleteCookiesNames of manage() class.

 this.driver.Manage().Cookies.DeleteCookieNamed("CookieName");

 

How to Maximize the Window in The Test Script

Sometimes, you need to test the scripts in full window size and resolution. You can easily do it by using the manage() method of driver instance. You can then use the method window() followed by maximize()to take the window to the maximum size.  

Code snippet is as below:

public void MaximizeWindow()
{
    this.driver.get(“");
    this.driver.Manage().Window().Maximize();
}

Conclusion

Selenium is one of the best tools for automation testing. You can follow these important tricks and tips to run your Selenium tests. If you will keep these in mind, you will solve the majority of your problems while scripting in Selenium WebDriver.

Topics:
selenium, selenium automation testing, selenium scripts, selenium tips

Published at DZone with permission of Chirag Thumar . See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}