top of page

Selenium Features

In this blog we will learn some common Selenium features which we will be using in most our project. These features will be widely used in project.

Launching a browser with all settings for the browser

ChromeOptions chromeOptions = new ChromeOptions();		chromeOptions.setPageLoadStrategy(PageLoadStrategy.NORMAL);
chromeOptions.setPageLoadTimeout(Duration.ofMillis(30000));			chromeOptions.setImplicitWaitTimeout(Duration.ofSeconds(20));
	driver=new ChromeDriver(chromeOptions);

Counting number of rows and columns in a table

Row = tr

List<WebElement> rows=driver.findElements(By.tagName("tr"));
		int noOfRows=rows.size();
		System.out.println("no of rows  :" +noOfRows );

Column= th

List<WebElement> columms=driver.findElements(By.tagName("th"));
		int noOfColumns=columms.size();
		System.out.println("no of columns  :" +noOfColumns );

Sample Code to find number of Rows and Columns


// **************  FINDING NO OF ROWS   ****************************************

//List<WebElement> hospitals=driver.findElements(By.xpath("//strong[contains(text(),'Hospital')]"));
List<WebElement> rows=driver.findElements(By.xpath("//tbody/tr"));
//List<WebElement> rows=driver.findElements(By.xpath("//tr"));
			int rows_count=rows.size();
	System.out.println("No Of Hospitals rows :" + rows_count);

// *************   FINDING NO OF COLUMNS  ***************************************	
			List<WebElement> columns=driver.findElements(By.xpath("//tr[1]//td"));
			int column_count=columns.size();
	System.out.println("No Of Hospitals columns:" + column_count);

To get the data and print the text written in first row first column of a table


// FINDING THE NAME OF THE HOSPITAL IN  FIRST ROW FIRST COLUMN [1][1]  ********************************************
			WebElement firstHospital=driver.findElement(By.xpath("//tr[1]//strong"));

			String hospitalNmae=firstHospital.getText();
			System.out.println(" first hospital name:" + hospitalNmae);

			String hospitalName=firstHospital.getText();
			System.out.println(" first hospital name:" + hospitalName);

Getting and Printing data in first column in a table


//**************  FINDING THE ALL HOSPITAL NAMES IN FIRST COLUMN     *********************

	for(int i=1;i<=rows_count;i++)
				WebElement eachHospital=driver.findElement(By.xpath("//tr["+i+"]//strong"));
				String hospitalName1=eachHospital.getText();
				System.out.println("Names of the Hospital : " +hospitalName1);

Getting data from each row and each column from a table


// GETTING DETAILS OF EACH HOSPITAL  finding all rows and column values       ************************************************
		for(int i=1;i<=rows_count;i++)
				for(int j=1;j<=column_count;j++)
				WebElement eachHospitalDetails=driver.findElement(By.xpath("//tr["+i+"]/td["+j+"]"));
				String hospitalDetails=eachHospitalDetails.getText();
				System.out.println(hospitalDetails );

Moving cursor from top to down to some extent

Using Scroll

JavascriptExecutor jse= (JavascriptExecutor) driver;	
			jse.executeScript("scroll(0, 3050)");	

Using ScrollIntoView

JavascriptExecutor jse = (JavascriptExecutor)driver;
				WebElement table=driver.findElement(By.xpath("//div[@role='rowgroup']"));
		jse.executeScript("arguments[0].scrollIntoView()", table);

To Click a particular element

JavascriptExecutor jse = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click()", hosp_name);

How to take Single Screenshot

	TakesScreenshot screenshot3 =( TakesScreenshot) driver; 
			File sourceFile3=screenshot3.getScreenshotAs(OutputType.FILE);
			File destinationFile3 = new File("C://Users//Reka//eclipse-workspace//Reka_Selenium_NN//src//test//java//Selenium//sample.png");  
			//FileUtils.copyFile(sourceFile3, destinationFile3); 
			FileHandler.copy(sourceFile3, destinationFile3);

How to have multiple Screenshot

	public void CollectionscreenShot(String fileName) throws IOException {    
        TakesScreenshot screenshot =( TakesScreenshot) driver; 
        File sourceFile=screenshot.getScreenshotAs(OutputType.FILE);
        File destinationFile = new File("C:\\Users\\Reka\\git\\DS-ALGO-94NN\\screenshot\\"+fileName);
        FileHandler.copy(sourceFile, destinationFile);

Calling the screenshot method


To Clear the text in input box and then send input

		driver.findElement(city).sendKeys(Keys.CONTROL + "A");
		driver.findElement(city).sendKeys(Keys.CONTROL + "X");

To select an element from DropDown


selectByVisibleText (" string ")

selectByIndex(int )

selectByValue(" " )

	//selecting multiple values from dropdown   		
		WebElement dropArrow=driver.findElement("j_idt87:auto-complete_input"));
		Select fromdrop=new Select(dropArrow);

Accept a ALERT


		WebElement okalert=driver.findElement(By.xpath("//*[@id=\"contentblock\"]/section/div[1]/div/div/button"));;
		Alert alertwindow=driver.switchTo().alert();

Dismiss a ALERT


		WebElement confirmBox=driver.findElement(By.xpath("//*[@id=\'contentblock\']/section/div[2]/div/div/button"));;
		Alert alertwindow1=driver.switchTo().alert();

PromptBox send text and accept


		WebElement promptBox=driver.findElement(By.xpath("//*[@id=\'contentblock\']/section/div[3]/div/div/button"));;
		Alert alertwindow2=driver.switchTo().alert();		

Drag and Drop using Actions


		WebElement sourceDrag=driver.findElement(By.xpath("//*[@id=\'draggable\']/p")) ;
		WebElement targetDrop=driver.findElement(By.xpath("//div[@id='droppable']"));
		Actions  actions=new Actions(driver);

To list number of options


		List<WebElement> listOfOption=selectfrom.getOptions();
		int sizeoflist= listOfOption.size();

Total number of Links with tagname "a"

		List<WebElement> totalLinks= driver.findElements(By.tagName("a"));
		int noOfLinks=totalLinks.size();

Windows Handling

It is a unique identifier that holds the address of all the windows. Think of it as a pointer to a window, which returns the string value. It is assumed that each browser will have a unique window handle.

getWindowHandle() returns the window handle of currently focused window/tab.

Return type of getWindowHandle() is String

String parentWindow=driver.getWindowHandle();
		System.out.println("Parent window:  "+parentWindow);

Parent window: 606B3572AF4640B4B85508F22A9E6B76

getWindowHandles() returns all windows/tabs handles launched/opened by same driver instance including all parent and child window.

Return type of getWindowHandles() is Set<String>

switchTo(): Using this method, we can perform switch operations within windows.

When you click a Link , you don't know how many windows will open , so put loop and to get all window id's and move to new window

		Set<String> windows=driver.getWindowHandles();
		for (String windowid : windows)
			//to move to newly opened window

Navigate back to Main Page


If child window is not equal to parent window, close child window if parent window is equal to parent window then exit loop

for (String windowidno : windows)
			if (!windowidno.equals(parentWindow))

Selenium Waits

In automation testing, wait commands direct test execution to pause for a certain length of time before moving onto the next step. This enables WebDriver to check if one or more web elements are present/visible/enriched/clickable, etc.

What are the three types of wait in Selenium?

Implicit, Explicit and Fluent Wait are the different waits used in Selenium. Usage of these waits are totally based on the elements which are loaded at different intervals of time. It is always not recommended to use Thread.Sleep() while Testing our application or building our framework.

Implicit wait

Implicit wait stays in place for the entire duration for which the browser is open. The default value of implicit wait is 0. Implicit wait is applied for the lifetime of the Webdriver, it can extend the test execution times to a large value depending on the number of elements on which it is being called.

An implicit wait is to tell WebDriver to poll the DOM for a certain amount of time when trying to find an element or elements if they are not immediately available. The default setting is 0, meaning disabled

The main function of implicit Wait is to tell the web driver to wait for some time before throwing a "No Such Element Exception". Its default setting is knocked at zero. Once the time is set, the driver automatically will wait for the amount of time defined by you before throwing the above-given exception.

driver.manage().timeouts().implicitlyWait(TimeOut, TimeUnit.SECONDS);  

Explicit Wait

Explicit Waits also known as Dynamic Waits because it is highly specific conditioned. It is implemented by WebDriverWait class. To understand why you need Explicit Wait in Selenium, you must go through the basic knowledge of the wait statements in a program. In simple terms, you must know some conditions.

In the syntax, create an object of WebDriver wait and passed driver reference and timeout as parameters.

 WebDriverWait wait=new WebDriverWait(WebDriveReference,TimeOut); 

Fluent Wait

Fluent Wait is quite similar to explicit Wait. It is similar in terms of management and functioning. In Fluent Wait, you can perform wait for action for an element only when you are unaware of the time it might take to be clickable or visible. Few differential factors that Fluent offers are as follows:

The pooling frequency

The pooling frequency in the case of Explicit is 500 milliseconds. But, using Fluent Wait, this pooling frequency can be changed to any value based upon your need. This usually means telling the script to keep an eye on the element after every 'x' seconds.

Ignore Exception

While pooling, if an element is not found, you can ignore some expectations like 'NoSuchElement'. Apart from this factor, similar to Explicit and Implicit Wait, you can define the amount of time for the element to be actionable or visible.


 Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver)  
       .withTimeout(60, SECONDS) // this defines the total amount of   
time to wait for  
       .pollingEvery(2, SECONDS) // this defines the polling frequency  
       .ignoring(NoSuchElementException.class); // this defines the   
exception to ignore   
      WebElement elemnent = fluentWait.until(new Function<WebDriver,  
     public WebElement apply(WebDriver driver)  //in this method   
defined your own subjected conditions for which we need to wait for  
     { return driver.findElement("element"));  


I hope, This article will help you to understand Selenium features which will be used mostly for every project. This blog will be handy to refer features and use in our project,

You must have got an idea on the topics explained in this blog. Lets explore more and learn New Topics.

Happy Learning

8 views0 comments
bottom of page