fbpx
Select Page

Selenium Scripting Tips and Tricks

As we have already seen the “11 Reasons: Why To Use Selenium for Automation Testing” previous article. (follow below link for the previous reference)  “https://www.sevenmentor.com/blog/11-reasons-why-to-use-selenium-for-automation-testing/”So continue this discussion we are moving towards some important tricks to use selenium as automation testing tool.

If you are just started to learn the Selenium automation testing tool then the below some tricks and tips will be helpful. These tips and tricks have all the basic things in 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.

Create a Web Driver Instance

You can make your tests generic. The first step will be initializing the browser bypassing 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 examine 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 (Webdriver)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”);

or

drp.selectByValue(“select value”);

or

drp.selectByIndex(select index number);

Navigate a Web Page in WebDriver

The navigate command in selenium exposes the ability to move backwards and forwards in the browser’s history.

If you want to refresh the page then you can use refresh() method to actually refresh the page.

forward() :  – This method or command does the same operation as clicking on the Forward Button of web browser.

back() : – This method does the same operation as clicking on the Back Button of  web browser.

to(String arg0) :– This method Loads a new web page in the current browser window.

driver.navigate().refresh();

driver.navigate().forward();

driver.navigate().back();

driver.navigate().to(“URL”);

How to Use Get Commands In Webdriver

Command – driver.get(siteUrl);

This method launches a new web page in the browser window. It allows String as a parameter and returns a void i.e. nothing.

Command – driver.getTitle();

This method returns the title string of the current page in the browser. It does not allow any parameter and its return type is a String.

Command – driver.getCurrentTitle();

This method returns the string containing the URL currently opened in the browser window. It does not allow any parameter and its return type is a String. It is one of the rarely used Selenium Webdriver commands, but sometimes it is helpful to use for logging purpose.

Command – driver.getPageSource();

This method retrieves the Source Code of a web page. It does not allow any parameter and its return value is a String.

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);

Switch to Iframe Window

What is Iframe?

IFrame is a web page which is fixed in another web page or it is an HTML document embedded inside another HTML document.

The <iframe> tag specifies an inline frame.

1

2

3

4

5

6

7

8

9

10

<html>

<body>

<div class=”box”>

<iframe name=”iframe1″ id=”IF1″ height=”600″ width=”400″ src=”http://toolsqa.com”></iframe>

</div>

<div class=”box”>

<iframe name=”iframe2″ id=”IF2″ height=”600″ width=”400″ align=”left” src=”http://demoqa.com”></iframe>

</div>

</body>

</html>

 

Ideally, we can switch over the elements in the iframes using 3 ways.

  • By Index
  • By Name or Id
  • By Web Element

Untitledpic

To Switch into iFrames we have to use the driver’s switchTo().frame command.

We can use the switchTo().frame() in three ways:

  • frame(int frameNumber): Pass the frame index and driver will switch to that frame.
  • frame(string frameName Or Id): Pass the frame element Name or ID and driver will switch to that frame.
  • frame(WebElement frameElement): Pass the frame web element and driver will switch to that frame.
  • How to find total number of iFrames on a webpage

  

For Free Demo classes Call:  8237077325
Registration Link: Click Here!
 

 

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();

 

How to Perform Right Click Operation

If you want to perform right click operation over an web element, you can use the Actions() class to handle it. You can use command contextClick() and then build() and perform() in a sequence to perform right click operation on a web element.

Actions action = new Actions(driver);

WebElement item = driver.findElement(By.xpath(“”));

action.contextClick(item).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 tool where we have know. You can follow these important tricks and tips to run your Selenium test script. If you will keep these in mind, you will solve the majority of your problems while scripting in Selenium WebDriver.

 

Author:

Name: Revati  Raspayle
Sevenmentor Pvt Ltd

Call the Trainer and Book your free demo Class for now!!!

call icon

© Copyright 2019 | Sevenmentor Pvt Ltd.






Pin It on Pinterest