isDisplayed, isSelected, isEnabled in Selenium

HOME

This tutorial describes how to check the state of a WebElement.

In this tutorial, we will learn isDisplayed, isEnabled, isSelected method in Selenium, and how to check the state of a WebElement. There are many methods which are used to determine the visibility scope for the web elements – isSelected(), isEnabled() and isDispalyed().

Many a time a test fails when we click on an element or enter text in a field. This is because the element is displayed or exist in DOM, but it does not exist on the web page.

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.

  • isDisplayed()
  • isSelected()
  • isEnabled()
  1. Boolean isSelected(): This method determines if an element is selected or not. It returns true if the element is selected and false if it is not. It is widely used on check boxes, radio buttons and options in a select.

2. Boolean isDisplayed(): This method determines if an element is displayed or not. It returns true if the element is displayed and false if it is not. Advantage of this method is that it avoids parsing an elements style attribute.

3. Boolean isEnabled(): This method determines if an element is enabled or not. It returns true if element is enabled (All elements apart from disabled input elements) and false if otherwise.

Steps to follow to understand when an element isEnabled and isDisplayed.

  1. Launch the web browser and open the application under test – https://duckduckgo.com/
  2. Verify the web page title
  3. Verify if the “Search Box” is displayed
  4. Verify that the “Search Box” is enabled
  5. If Search Box is enabled, then search for text – Selenium
  6. Close the browser
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class VerifyConditionsDemo {

	public static void main(String[] args) {

		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");
		
WebDriver driver = new FirefoxDriver();

		// launch the firefox browser and open the application url
		driver.get("https://duckduckgo.com/");

		// maximize the browser window
		driver.manage().window().maximize();

		// declare and initialize the variable to store the expected title of the
		// webpage.
		String expectedTitle = "DuckDuckGo — Privacy, simplified.";

		// fetch the title of the web page and save it into a string variable
		String actualTitle = driver.getTitle();

		// compare the expected title of the page with the actual title of the page and
		// print the result
		if (expectedTitle.equals(actualTitle)) {
			System.out.println("Verification Pass- The correct title is displayed on the web page.");
		} else {
			System.out.println("Verification Failed - An incorrect title is displayed on the web page.");
		}

		// verify that the “Search" Box is displayed
		WebElement searchBox = driver.findElement(By.id("search_form_input_homepage"));
		if (searchBox.isDisplayed()) {
			System.out.println("Search Box is visible. Return: " + searchBox.isDisplayed());
		} else {
			System.out.println("Search Box is not visible. Return: " + searchBox.isDisplayed());
		}

		// verify that the “Search” Box is enabled
		if (searchBox.isEnabled()) {
			System.out.println("Search Box is enabled. Return: " + searchBox.isEnabled());
			searchBox.sendKeys("Selenium");
		} else {
			System.out.println("Search Box is not enabled. Return: " + searchBox.isEnabled());
		}

		System.out.println("Successful Execution of Test.");

		// close the web browser
		driver.close();

	}
}

Output
Verification Pass- The correct title is displayed on the web page.
Search Box is visible. Return: true
Search Box is enabled. Return: true
Successfull Execution of Test.

isSelected

Steps to follow to understand when an element is Selected or not.

  1. Launch the web browser and open the application under test – https://www.seleniumeasy.com/test/basic-radiobutton-demo.html
  2. Verify if first Radio Button (Male) is selected or not
  3. If first radio button is already selected, then select Radio Button 2, else vice versa.
  4. Print the value of selected Radio Button
  5. Print the value of selecting a Radio Button
  6. Close the browser

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class isSelectedDemo {

	public static void main(String[] args) {
		System.setProperty("webdriver.gecko.driver",
				"C:\\Users\\Vibha\\Software\\geckodriver-v0.26.0-win64\\geckodriver.exe");

		FirefoxDriver driver = new FirefoxDriver();
		driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
		driver.get("https://www.seleniumeasy.com/test/basic-radiobutton-demo.html");

		List<WebElement> Radio_Options = driver.findElements(By.name("optradio"));

		// Create a boolean variable which will hold the value (True/False)
		boolean radio_value = false;

		// This statement will return True, in case of first Radio button is selected
		radio_value = Radio_Options.get(0).isSelected();

		// Identify if Radio Button 1 is selected or not. If Button 1 is already
		// selected, then select Button 2
		if (radio_value == true) {
			Radio_Options.get(1).click();
			System.out.println("Button Selected is :" + Radio_Options.get(1).getAttribute("value"));
		} else {
			Radio_Options.get(0).click();
			System.out.println("Button Selected is :" + Radio_Options.get(0).getAttribute("value"));
		}

		driver.findElement(By.id("buttoncheck")).click();
		String Button_Selected = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[1]/div[2]/p[3]"))
				.getText();
		System.out.println("Get Checked Value is :" + Button_Selected);

		// close the web browser
		driver.close();
	}
}

That’s it! Congratulations on making it through this tutorial and hope you found it useful! Happy Learning!! Cheers!!

Selenium Interview Questions and Answers for 2021

HOME

1. What are the different types of locators in Selenium?

Locator is unique address of any web element on web page. Locating elements in WebDriver is done by using the method “findElement(By.locator())”. 
Here, locator() part will be replaced with locator names, like

driver.findElement(By.id(“email”)) 
Types of Locators in Selenium

  • ID
  • ClassName
  • Name
  • TagName
  • LinkText
  • PartialLinkText
  • Xpath – Absolute Path & Relative Path
  • CSS Selector

For more details, click here

 
2. What is an XPath?

XPath is used to locate a web element based on its XML path. The fundamental behind locating elements using XPath is the traversing between various elements across the entire page and thus enabling a user to find an element with the reference of another element 
Various functions used in XPath are:-
1) text()
2) contains()
3) last()
4) AND , OR
5) position()
6) following()
7) preceding()

For more details, click here

3. What is the difference between “/” and “//” in XPath?

Single Slash “/” – Single slash is used to create XPath with absolute path i.e. the XPath would be created to start selection from the document node/start node. Example is given below 

driver.findElement(By.xpath("//*[@id='yDmH0d']/div/div[2]/div[2]/form/content/section/div/content/div/input")

Double Slash “//” – Double slash is used to create XPath with relative path i.e. the XPath would be created to start selection from anywhere within the document. Example is given below

driver.findElement(By.id("email"))

For more details, click here

4. How do we can launch the browser using WebDriver?

Firstly, we should instantiate a Chrome/Chromium session by doing the following

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
           WebDriver driver = newChromeDriver();

Set the path to the chromedriver executable

System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Automation\\Drivers\\chromedriver_win32\\chromedriver.exe");

The chromedriver is implemented as a WebDriver remote server that instructs the browser what to do by exposing Chrome’s internal automation proxy interface.

Firefox

Similarly, we can launch other browsers too like Firefox, InternetExplorer, Edge

    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.Firefox.FirefoxDriver;
System.setProperty("webdriver.gecko.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\geckodriver-v0.26.0-win64\\geckodriver.exe");
        WebDriver driver = new FirefoxDriver();

MicroSoftEdge

     import org.openqa.selenium.WebDriver;
     import org.openqa.selenium.edge.EdgeDriver;
 System.setProperty("webdriver.edge.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\edgedriver_win64\\msedgedriver.exe");
          WebDriver driver = new EdgeDriver();

For more details, click here 

5. What are the different types of Drivers available in WebDriver?

The different drivers available in WebDriver are

  • FirefoxDriver
  • InternetExplorerDriver
  • ChromeDriver
  • SafariDriver
  • OperaDriver
  • AndroidDriver
  • IPhoneDriver
  • HtmlUnitDriver

6. Explain the different exceptions in Selenium WebDriver

Exceptions in Selenium are similar to exceptions in other programming languages. The most common exceptions in Selenium are:
1. TimeoutException: This exception is thrown when a command performing an operation does not complete in the  expected time.

2. NoSuchElementException: This exception is thrown when an element with given attributes is not found on the web page. Suppose webdriver is trying to click on XPath – “//*[@id=’yDmH0d’]/div/div[2]/div[2]/form/content” which doesn’t exist on that particular web page, then below exception is displayed – org.openqa.selenium.NoSuchElementException.


3. ElementNotVisibleException: This exception is thrown when the element is present in DOM (Document Object Model), but not visible on the web page.

4. StaleElementException: This exception is thrown when the element is either deleted or no longer attached to the DOM.

7. What are the different types of waits available in WebDriver? or 

How do you achieve synchronization in WebDriver?

There are three types of wait in Selenium WebDriver

 1.   Implicit Wait – The implicit wait will tell to the web driver to wait for certain amount of time before it throws a “NoSuchElementException“. The default setting is 0. Once we set the time, web driver will wait for that time before throwing an exception. Implicit waits are used to provide a default waiting time (say 30 seconds) between each consecutive test step/command across the entire test script.
We need to import java.util.concurrent.TimeUnit to use ImplicitWait.

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

2.    Explicit Wait – An explicit wait is code you define to wait for a certain condition to occur before proceeding further in the code. The explicit wait will tell the web driver to wait for certain conditions like visibilityOfElementLocated and maximum amount of time before throwing NoSuchElementException exception. Unlike Implicit waits, explicit waits are applied for a particular instance only.

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Stats1_totalCount")));

3.  Fluent Wait – Fluent Wait instance defines the maximum amount of time to wait for a condition, as well as the frequency with which to check the condition.

Users may configure the wait to ignore specific types of exceptions whilst waiting, such as  NoSuchElementException when searching for an element on the page.

Fluent Wait commands are mainly used when the web elements which sometimes visible in few seconds and some times take more time than usual. Mainly in Ajax applications. We could set the default pooling period based on the requirement.

Wait wait = new FluentWait(driver)  .withTimeout(Duration.ofSeconds(30))
 .pollingEvery(Duration.ofSeconds(5))
.ignoring(NoSuchElementException.class);

WebElement foo = wait.until(new Function() {
public WebElement apply(WebDriver driver) {
     return driver.findElement(By.id("foo"));
}
});

For more details, click here 

8. How to set size of Window in Selenium WebDriver?

First fetch the size of the browser window in pixels by below shown code Dimension

size = driver.manage().window().getSize();
         int width1 = size.getWidth();
         int height1 = size.getHeight();

Now, change the size of window by using

driver.manage().window().setSize(new Dimension(1024, 768)); 

9. How to set position of Window in Selenium?

First fetch the coordinates of the top left coordinate of the browser window by

Point position = driver.manage().window().getPosition();
         int x1 = position.getX();
         int y1 = position.getY();

The window can be moved to the chosen position by

// Move the window to the top left of the primary monitor
driver.manage().window().setPosition(new Point(0, 0));

10. What is the difference between driver.findElement() and driver.findElements() commands?

FindElement – This method locates for the first web element on the current web page matching the criteria mentioned as parameter.  
If the web element is not found, it will throw an exception – NoSuchElementException. 

driver.findElement(By.xpath("Xpath location"));

FindElements – This method locates all the web elements on the current web page matching the criteria mentioned as parameter. 

If not found any WebElement on current page as per given element locator mechanism, it will return empty list.     

findElements (By arg0):List<WebElement

For more details, click here 

11. How to type in a textbox using Selenium?

The user can use sendKeys(“String to be entered”) to enter the string in the textbox. The sendKeys types a key sequence in DOM element even if modifier key sequence is encountered.

Syntax - sendKeys(CharSequence… keysToSend ) : void
Command – driver.findElement(By.xpath("//*[@name = 'email']")).sendKeys("abc123@gmail.com") 

For more details, click here

12. How can we get a text of a web element?

Get command is used to retrieve the inner text of the specified web element. The command doesn’t require any parameter but returns a string value. It is also one of the extensively used commands for verification of messages, labels, errors etc displayed on the web pages. 

String Text = driver.findElement(By.id(“Text”)).getText();

13. How to input text in the text box without calling the sendKeys()?

//Creating the JavascriptExecutor interface object by Type casting                                     JavascriptExecutor js = (JavascriptExecutor)driver;              
//Launching the Site        
driver.get("https://www.google.com/");                      js.executeScript("document.getElementsByName('q')[0].value = 'Selenium Introduction';");

For more details, click here

14. How to read a JavaScript variable in Selenium WebDriver? 

//To initialize the JS object
JavascriptExecutor JS = (JavascriptExecutor) webdriver;
//To get the site title
String title = (String)JS.executeScript("return document.title");
System.out.println("Title of the webpage : " + title);

For more details, click here

15. What is JavaScriptExecutor and in which cases JavaScriptExecutor will help in Selenium automation?

There are some conditions where we cannot handle some problems with WebDriver only, web controls don’t react well against selenium commands. In this kind of situations, we use Javascript. It is useful for custom synchronizations, hide or show the web elements, change values, test flash/HTML5 and so on. 
In order to do these, we can use Selenium’s JavascriptExecutor interface which executes JavaScript through Selenium driver.

It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

JavascriptExecutor js = (JavascriptExecutor) driver; 
js.executeScript(Script,Arguments);

Script – This is the JavaScript that needs to execute.

Arguments – It is the arguments to the script. It’s optional
Let’s see some scenarios we could handle using this Interface:
1. To type Text in Selenium WebDriver without using sendKeys() method 2. To click a Button in Selenium WebDriver using JavaScript
3. To handle Checkbox
4. To generate Alert Pop window in selenium
5. To refresh browser window using Javascript
6. To get innertext of the entire webpage in Selenium
7. To get the Title of our webpage
8. To get the domain
9. To get the URL of a webpage
10. To perform Scroll on an application using  Selenium


For more details, click here

16. How To Highlight Element Using Selenium WebDriver?

By using JavascriptExecutor interface, we could highlight the specified element

//Create the JavascriptExecutor interface object by Type casting               JavascriptExecutor js = (JavascriptExecutor)driver; 

//Higlight element - Total PageCount
WebElement TotalCount = driver.findElement(By.id("Stats1"));js.executeScript("arguments[0].style.border='3px dotted blue'", TotalCount); 

For more details, click here

17. List some scenarios which we cannot automate using Selenium WebDriver?

1. Bitmap comparison is not possible using Selenium WebDriver.
2. Automating Captcha is not possible using Selenium WebDriver.
3. We can not read bar code using Selenium WebDriver.

18. How can you find if an element in displayed on the screen?

WebDriver facilitates the user with the following methods to check the visibility of the web elements. These web elements can be buttons, drop boxes, checkboxes, radio buttons, labels etc.

  • isDisplsyed()
  • isSelected()
  • isEnabled()
isDisplayed():
boolean elePresent = driver.findElement(By.xpath("xpath")).isDisplayed();
isSelected():
boolean eleSelected= driver.findElement(By.xpath("xpath")).isSelected(); 
isEnabled():
boolean eleEnabled= driver.findElement(By.xpath("xpath")).isEnabled();

19. Explain how you can switch back from a frame?

To switch back from a frame use method defaultContent()  

driver.switchTo().defaultContent(); 

20. What is the difference between getWindowhandles() and getwindowhandle() ?

getwindowhandles(): It is used to get the address of all the open browser and its return type is Set<String>

getwindowhandle(): It is used to get the address of the current browser where the control is and return type is string.

For more details, click here

21. How to select value in a dropdown?

To perform any operation on DropDown, we need to do 2 things:-

1) Import package org.openqa.selenium.support.ui.Select 
2) Create new Select object of class Select

Select oSelect = new Select());
Different Select Commands
  1. selectByValue
Select yselect = new Select(driver.findElement(By.id("year")));
yselect.selectByValue("1988");

2. selectByVisibleText

 Select mselect = new Select(driver.findElement(By.id("month")));
 mselect.selectByVisibleText("Apr");

3. selectByIndex

Select bselect = new Select(driver.findElement(By.name("birthday_day")));
bselect.selectByIndex(8);

For more details, click here

22. How to switch to a new window (new tab) which opens up after you click on a link?

If you click on a link in a web page and it opens a new window, but WebDriver will not know which window the Operating system consider active. To change the WebDriver’s focus/ reference to the new window we need to use the switchTo() command. driver.switchTo().window();

Here, ‘windowName’ is the name of the window you want to switch your reference to.

In case you do not know the name of the window, then you can use the driver.getWindowHandle() command to get the name of all the windows that were initiated by the WebDriver. Note that it will not return the window names of browser windows which are not initiated by your WebDriver.

Once you have the name of the window, then you can use an enhanced for loop to switch to that window. Look at the piece of code below.

String handle= driver.getWindowHandle();
for (String handle : driver.getWindowHandles()) 
{
driver.switchTo().window(handle); 
}

//Store the ID of the original window
String originalWindow = driver.getWindowHandle();

//Check we don't have other windows open already
 assert driver.getWindowHandles().size() == 1;

 //Click the link which opens in a new window
 driver.findElement(By.linkText("new window")).click();

 //Wait for the new window or tab
 wait.until(numberOfWindowsToBe(2));
  
//Loop through until we find a new window handle
for (String windowHandle : driver.getWindowHandles()) {
    if(!originalWindow.contentEquals(windowHandle)) {
        driver.switchTo().window(windowHandle);
        break; 
    } 
}
  
//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"));  

For more details, click here

23. How to handle browser (chrome) notifications in Selenium?

In Chrome, we can use ChromeOptions as shown below.

ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
WebDriver player = new ChromeDriver(options);

24. How to delete Browser Cookies with Selenium Web Driver?

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

25. What are the different types of navigation commands?

  • driver.navigate().forward(); – to navigate to the next web page with reference to the browser’s history.
  • driver.navigate().back(); – takes back to the previous webpage with reference to the browser’s history.
  • driver.navigate().refresh(); – to refresh the current web page thereby reloading all the web elements.
  • driver.navigate().to(“url”); – to launch a new web browser window and navigate to the specified URL.

For more details, click here

26. How can we handle Web-based Pop-ups or Alerts in Selenium?

To handle Web-based alerts or popups, we need to do switch to the alert window and call Selenium WebDriver Alert API methods.

  • dismiss(): To click on Cancel button.
  • accept(): To Click on OK button.
  • getText(): To get the text which is present on the Alert.
  • sendKeys(): To enter the text into the alert box.

For more details, click here

27. What are the ways to refresh a browser using Selenium WebDriver?

1. Using driver.navigate().refresh() command.
2. Using driver.get(“URL”) on the current URL or using driver.getCurrentUrl()
3. Using driver.navigate().to(“URL”) on the current URL or driver.navigate().to(driver.getCurrentUrl());
4. Using sendKeys(Keys.F5) on any textbox on the webpage.        

28. What is Page Object Model in Selenium?

Page Object is a Design Pattern which has become popular in test automation for enhancing test maintenance and reducing code duplication. A page object is an object-oriented class that serves as an interface to a page of your AUT. The tests then use the methods of this page object class whenever they need to interact with the UI of that page. The benefit is that if the UI changes for the page, the tests themselves don’t need to change, only the code within the page object needs to change. Subsequently all changes to support that new UI are located in one place.
The Page Object Design Pattern provides the following advantages:
There is a clean separation between test code and page specific code such as locators (or their use if you’re using a UI Map) and lay
There is a single repository for the services or operations offered by the page rather than having these services scattered throughout the tests.

For more details, click here

29. What are the different mouse actions that can be performed?

The different mouse events supported in selenium are
1. click(WebElement element)
2. doubleClick(WebElement element)
3. contextClick(WebElement element)
4. mouseDown(WebElement element)
5. mouseUp(WebElement element)
6. mouseMove(WebElement element)
7. mouseMove(WebElement element, long xOffset, long yOffset)

For more details, click here

30Write the code to double click an element in selenium?

Code to double click an element in selenium is mentioned below

Actions action = new Actions(driver);
   WebElement element=driver.findElement(By.id("elementId"));
   action.doubleClick(element).perform();

31. Write the code to right-click an element in selenium?

Code to right-click an element in selenium is mentioned below-

   Actions action = new Actions(driver);
   WebElement element=driver.findElement(By.id("elementId"));
    action.contextClick(element).perform();

32. How to mouse hover an element in selenium?

Code to mouse hover over an element in selenium is mentioned below:-

Actions action = new Actions(driver);
   WebElement element=driver.findElement(By.id("elementId"));
    action.moveToElement(element).perform();

33. How to do drag and drop in Selenium?

Using Action class, drag and drop can be performed in selenium.

    Actions builder = new Actions(driver);
    Action dragAndDrop = builder.clickAndHold(SourceElement).moveToElement(TargetElement).release(TargetElement).build();
    dragAndDrop.perform();

    Or
  // Create object of actions class
      Actions builder = new Actions(driver);
                       
  // Perform drag and drop operation
       builder.dragAndDrop(from, to).build().perform();

For more details,click here

34. How can we capture screenshots in selenium?

Using the getScreenshotAs method of TakesScreenshot interface, we can take the screenshots in selenium.

File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("D:\\testScreenShot.jpg"));

Difference between getText() and getAttribute() method in Selenium WebDriver

In this tutorial, we will discuss about GetText() method as well as getAttribute() method in Selenium WebDriver. These methods used extensively in automating a web application. Before going through these methods, we should know what HTML attributes are.

What are HTML attributes?

Attributes are the additional information provided by developers in HTML tags. Attributes are normally defined using “name-pair” values. Let us see, here div is the tag and corresponding attribute with property name is id and property value is nav-xshop.
<div id= “nav-xshop”>


What is getAttribute() method?

The getAttribute() method is declared in the WebElement interface, and it returns the value of the web element’s attribute as a string. It fetches the value of an attribute, in HTML code whatever is present in the left side of ‘=’ is an attribute, value on the right side is an attribute value.

  • getAttibute() returns ‘null’ if there no such attribute
  • getAttribute() method will return either “true” or null for attributes whose value is Boolean.

Where to use getAttribute() method?

Consider a scenario of movie ticket booking. The color of booked and available seats in movie theatre are different. So same seat will have suppose white color for available seat and blue for booked seat. So, the color attribute of seat changes from white to blue for same seat which can be identified by getAttribute() method. The snippet below shows the HTML code of search box of Amazon Home page

Below is an example on how getAttribute() method can be used.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class GetAttributeDemo {
      public static void main(String[] args) {
 
            System.setProperty("webdriver.chrome.driver",
                                                "C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
 
             WebDriver driver = new ChromeDriver();
 
             driver.get("https://www.amazon.com/");
             driver.manage().window().maximize();
 
             WebElement AmazonSearchBox = driver.findElement(By.name("field-keywords"));
             System.out.println("Name of the Email Textbox is:- " + AmazonSearchBox.getAttribute("name"));
 
             System.out.println("Class of the Email Textbox is:- " + AmazonSearchBox.getAttribute("class"));
 
             System.out.println("Value of the Email Textbox is:- " + AmazonSearchBox.getAttribute("tabindex"));
 
             System.out.println("Type of the Email Textbox is:- " + AmazonSearchBox.getAttribute("type"));
 
             System.out.println("Id of the Email Textbox is:- " + AmazonSearchBox.getAttribute("id"));
 
             // getAttibute() returns 'null' if there no such attribute
 
             System.out.println("Value of nonExistingAttribute is:- " + AmazonSearchBox.getAttribute("test"));
 
            driver.close();
       }
 
}

Output
Name of the Email Textbox is:- field-keywords
Class of the Email Textbox is:- nav-input
Value of the Email Textbox is:- 19
Type of the Email Textbox is:- text
Id of the Email Textbox is:- twotabsearchtextbox
Value of nonExistingAttribute is:- null

What is getText() method?

getText() is a method which gets us the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing white space.

Inner text is text between the opening tags and closing tags.

This is the example of getText

In above example, texts  “This is the example of getText” between opening and closing tags of h1 are called inner text.

The snippet below shows the HTML code of search box of Amazon Home page

Below is an example on how getText() method can be used.

import java.util.concurrent.TimeUnit;
 
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class GetTextDemo {
 
      public static void main(String[] args) {
           System.setProperty("webdriver.chrome.driver",
                                                "C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
 
            WebDriver driver = new ChromeDriver();
 
            driver.get("https://www.facebook.com/");
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
 
            String FacebookText = driver
                                    .findElement(By.xpath("//*[@id='content']/div/div/div/div/div[2]/div/div[1]/div[1]/span")).getText();
            System.out.println("Text on Facebook Site:- " + FacebookText);
         driver.close();
      }
 
}

Output
Text on Facebook Site:- Create an account

Execute JavaScript with executeAsyncScript() Method in Selenium

HOME

In the previous blog, we have discussed about executeScript() method in JavaScript. JavascriptExecutor interface comprises of executeAsyncScript() method that is called an additional final argument “arguments[arguments.lenght-1];”which is a callback function to signal that async execution has finished. We have to call from JavaScript, to tell Webdriver, that our Asynchronous execution has finished. If we do not do that, then executeAsyncScpriptwill timeout and throw a timeout exception.

Before executing AsyncScript method, we have to make sure to set the script timeout. Its default is 0. If we do not set a script timeout, our executeAsyncScript will immediately timeout and it won’t work.

Below is the program which shows how to use executeAsyncScript() method

  1. First  will get the start time before waiting 5 seconds by using executeAsyncScript() method.
  2. Then, will use executeAsyncScript() to wait 5 seconds.
  3. Then, will get the current time
  4. Will subtract (current time – start time) = passed time and print the value
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public classExecuteAsycSleepBrowserDemo {
        public static void main(String[] args) { 
    

System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = newChromeDriver();
                                        
        //Create the JavascriptExecutor interface object by Type casting              
        JavascriptExecutor js = (JavascriptExecutor)driver;              
        driver.get("https://www.google.com/");                              
        driver.manage().window().maximize();
                        
        //Declare and set start time
        long startTime = System.currentTimeMillis();
                 
        //Call executeAsyncScript() method                       js.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 5000);"); 
                 
        //Get the difference (currentTime - startTime) it should be greater than 5000
        System.out.println("Passed time: " + (System.currentTimeMillis() - startTime));
                        
          if ( (System.currentTimeMillis() - startTime) > 5000)
             {
                 System.out.println("Time difference must be greater than 5000 milliseconds");
             }
          driver.quit();      
      }

Output
Passed time: 5040
Time difference must be greater than 5000 milliseconds

Execute JavaScript with executeScript() Method in Selenium

HOME

In the previous tutorial, we have discussed about JavaScript. There are some conditions where we cannot handle some problems with WebDriver only, web controls don’t react well against selenium commands. In this kind of situations, we use Javascript. JavaScriptExecutor comes separately and also comes under the WebDriver but both do the same thing. Within the WebDriver, it is named as ExecuteScript.

JavaScriptExecutor is an interface that provides a mechanism to execute Javascript through selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

ExecuteScript Method – This method executes JavaScript in the context of the currently selected frame or window in Selenium. The script used in this method runs in the body of an anonymous function (a function without a name). We can also pass complicated arguments to it. 

Execute the below selenium script. In this example,

  • Launch the site
  • Fetch the domain name of the site.
  • Fetch the URL of the site
  • Fetch the title name of the sit
  • Then navigate to a different page – google.com
  • Display Alert popup                                                                        
package SeleniumTutorial;
import org.openqa.selenium.JavascriptExecutor;
 
import org.openqa.selenium.WebDriver;
 
import org.openqa.selenium.chrome.ChromeDriver;
 
public classJavaScript_Demo {
        public static voidmain(String[] args) {
                        System.setProperty("webdriver.chrome.driver","C:\\Users\\SingVi04\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
 
        WebDriver driver= new ChromeDriver();
                                        
        //Create the JavascriptExecutor interface object by Type casting                
        JavascriptExecutor js = (JavascriptExecutor)driver;             
 
        driver.get("https://configureselenium.blogspot.com/");
 
        driver.manage().window().maximize();
  
 
       //Fetching the Domain Name of the site. Tostring() change object to name.                
        String DomainName = js.executeScript("return document.domain;").toString();                 
        System.out.println("Domain name of the site = "+DomainName);                                        
                        
        //Fetching the URL of the site. Tostring() change object to name          
        String url = js.executeScript("return document.URL;").toString();                
        System.out.println("URL of the site = "+url);                                      
                        
        //Method document.title fetch the Title name of the site. Tostring() change object to name          
       String TitleName = js.executeScript("return document.title;").toString();                        
       System.out.println("Title of the page = "+TitleName);                                  
                
        //Navigate to new Page i.e to generate access page. (launch new url)             
        js.executeScript("window.location = 'https://www.google.com/'");
        String NewTitleName = js.executeScript("return document.title;").toString();                      
        System.out.println("Title of the new page = "+NewTitleName);    
 
        //Alert
        js.executeScript("alert('Hello Everyone!');");
        driver.switchTo().alert().accept();
      
        driver.quit();
    }           
 }

JavaScript and JavaScriptExecutor in Selenium

 
 
What is JavaScript?
 

JavaScript is the preferred language inside the browser to interact with HTML dom. This means that a Browser has JavaScript implementation in it and understands the JavaScript commands.
WebDriver gives you a method called Driver.executeScript which executes the JavaScript in context of the loaded browser page. There are some conditions where we cannot handle some problems with WebDriver only, web controls do not react well against selenium commands. In this kind of situations, we use Javascript. It is useful for custom synchronizations, hide or show the web elements, change values, test flash/HTML5 and so on. In order to do these, we can use Selenium’s JavascriptExecutor interface that executes JavaScript through Selenium driver.

What is JavaScriptExecutor?

JavaScriptExecutor comes separately and comes under the WebDriver but both do the same thing. Within the WebDriver, it is name as ExecuteScript. JavaScriptExecutor is an interface that provides a mechanism to execute Javascript through selenium driver. It provides “executescript” & “executeAsyncScript” methods, to run JavaScript in the context of the currently selected frame or window.

ExecuteScript Method

This method executes JavaScript in the context of the currently selected frame or window in Selenium. The script used in this method runs in the body of an anonymous function (a function without a name). We can also pass complicated arguments to it.

The script can return values. Data types returned are 

  • Boolean 
  • Long 
  • String 
  • List 
  • WebElement 
JavascriptExecutor js = (JavascriptExecutor) driver;  
js.executeScript(Script,Arguments);

Script – This JavaScript needs to execute.

Arguments – It is the arguments to the script. It is optional

Below is an example, which shows how executeScript method can be use. In this example, 

  1. Launch the site
  2. Scroll down by 600 pixel
  3. Refresh the page
  4. Highlight a particular element
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class JavaSE_Demo {
        public static void main(String[] args){        

System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver= new ChromeDriver();                         
 
        //Create the JavascriptExecutor interface object by Type casting              
         JavascriptExecutor js = (JavascriptExecutor)driver;                   
         driver.get("https://configureselenium.blogspot.com/");     
         driver.manage().window().maximize();               

         //Vertical scroll down by 600  pixels             
          js.executeScript("window.scrollBy(0,600)");                           
 
         //Refresh the page
          js.executeScript("history.go(0);");
                       
          //Higlight element - Total PageCount
          WebElement TotalCount= driver.findElement(By.id("Stats1"));
          js.executeScript("arguments[0].style.border='3px dotted blue'", TotalCount);                     
      }                          
}

How to enter text-using JavaScriptexecutor (Without Sendkeys)

import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class JavaScript_EnterText {
        public static void main(String[] args) {
        System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver = newChromeDriver();
                                        
         //Creating the JavascriptExecutor interface object by Type casting              
          JavascriptExecutor js = (JavascriptExecutor)driver;              
                                        
          //Launching the Site.         
          driver.get("https://www.google.com/");                      
                     
          //Maximize window            
          driver.manage().window().maximize();       
                        
          js.executeScript("document.getElementsByName('q')[0].value = 'Selenium Introduction';");
   } 
}   

How to automate Radio Button in Selenium WebDriver

HOME

 

In this tutorial, will find out how the Radio Buttons can automated in Selenium WebDriver. Radio Button is also a Web Element like Checkbox. 
Below image shows the Radio Buttons before they selected

Here, In below image Male option is selected and clicked on Get Checked value, then a message will be displayed.

Here,
Check if Option 1 is already selected or not
If Option 1 is already selected, then select Option 2, else select Option 1.

Let’s go through the scenario below:-

1) Launch Chrome Browser
2) Maximize the current window
3) Implicitly wait for 30 sec
4) Open browser – https://www.seleniumeasy.com/test/basic-radiobutton-demo.html.
5) Find locator of all Radio Buttons
6) Find no of Radio Buttons available and print their values
7) Verify that first Radio button is selected or not and print
8) Find the value of Get Checked Value button and print the value
9) Identify if Radio Button 1 selected or not. If Button 1 already selected, then select Button 2
10) Click on “Get Checked Value” button
11) Find the value of “Get Checked Value” button after selecting the option and print the value
12) Close the browser

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class RadioButtonDemo {
            public static void main(String[] args) throws InterruptedException {
 
                        System.setProperty("webdriver.chrome.driver", "src\\test\\resources\\webdrivers\\window\\chromedriver.exe");
 
                        // Initiate Chrome browser
                        WebDriver driver = new ChromeDriver();
 
                        // Maximize the browser
                        driver.manage().window().maximize();
 
                        // Put an Implicit wait and launch URL
                        driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
                        driver.get("https://www.seleniumeasy.com/test/basic-radiobutton-demo.html");
 
                        // Find locator of all Radio Buttons
                        List Radio_Options = driver.findElements(By.xpath("//*[@name='optradio']"));
 
                        // Find no of Radio Buttons available and print their values
                        int radioSize = Radio_Options.size();
                        System.out.println("No Of Radio Button Options :" + radioSize);
 
                        for (int i= 0; i< radioSize; i++) {
                                    System.out.println("Name of Radio Button :"+ Radio_Options.get(i).getAttribute("value"));
                        }
 
                        // Create a boolean variable which will hold the value (True/False)
                        boolean radio_value = false;
 
                        // This statement will return True, in case of first Radio button is selected
                        radio_value = Radio_Options.get(0).isSelected();
                        System.out.println("First Radio Option is Checked :" + radio_value);
 
                        // Find the value of "Get Checked Value" button and print the value
                        String preButtonSelected = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[1]/div[2]/p[3]"))
                                                .getText();
 
                        if (preButtonSelected.isEmpty() == true) {
                                    System.out.println("Get Checked Value before selection is Empty");
                        } else {
                                    System.out.println("Get Checked Value before selection is :" + preButtonSelected);
                        }
                        Thread.sleep(1000);
 
                        // Identify if Radio Button 1 is selected or not. If Button 1 is already
                        // selected, then select Button 2
                        if (radio_value == true) {
                                    Radio_Options.get(1).click();
                                    System.out.println("Button Selected is :"+ Radio_Options.get(1).getAttribute("value"));
                        } else {
                                    Radio_Options.get(0).click();
                                    System.out.println("Button Selected is :"+ Radio_Options.get(0).getAttribute("value"));
                        }
 
                        // Click on "Get Checked Value" button
                        driver.findElement(By.id("buttoncheck")).click();
 
                        // Find the value of "Get Checked Value" button after selecting 
                        // the option and print the value
                        String postButtonSelected = driver.findElement(By.xpath("//*[@id='easycont']/div/div[2]/div[1]/div[2]/p[3]"))
                                                .getText();
                        System.out.println("Get Checked Value is :"+ postButtonSelected);
                        Thread.sleep(1000);
 
                        // Close the browser
                        driver.close();
            }
}

Output
No Of Radio Button Options :2
Name of Radio Button :Male
Name of Radio Button :Female
First Radio Option is Checked :false
Get Checked Value before selection is Empty
Button Selected is :Male
Get Checked Value is :Radio button 'Male' is checked

How to automate BootStrap DropDown using Selenium WebDriver

 
In the previous post, we have already seen How to Handle Dropdowns in Selenium WebDriver . In this post, we will see how to handle Bootstrap Dropdown using Selenium WebDriver.
 
What is Bootstrap?
 
  • Bootstrap is a free front-end framework for faster and easier web development
  • Bootstrap includes HTML and CSS based design templates for typography, forms, buttons, tables, navigation, modals, image carousels and many other, as well as optional JavaScript plugins
  • Bootstrap also gives you the ability to easily create responsive designs
  • Bootstrap is compatible with all modern browsers (Chrome, Firefox, Internet Explorer, Edge, Safari, and Opera)

What is Responsive Web Design?

Responsive web design is about creating web sites, which automatically adjust themselves to look good on all devices, from small phones to large desktops.
Bootstrap dropdowns and interactive dropdowns that are dynamically position and formed using list of ul and li html tags. To know more about Bootstrap, please click here

 

How to get all the options of a Bootstrap dropdown


Below is an example which will explain how to get all the options of a Bootstrap dropdown.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
 
import org.openqa.selenium.chrome.ChromeDriver;
public class BootStrapDemo {
        public static void main(String[] args) {
 System.setProperty("webdriver.chrome.driver","C:\\Users\\SingVi04\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

          WebDriver driver= new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.seleniumeasy.com/test/");
          driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

                // Clicking on Bootstrap Dropdown
               driver.findElement(By.xpath("//*[@id='navbar-brand-centered']/ul[1]/li[1]/a")).click(); 

                // Get the all WebElements inside the dropdown in List  
               List dropdown_list =  driver.findElements(By.xpath("//ul[contains(@class,'dropdown-menu')]//li//a"));

              // Printing the amount of WebElements inside the list
               System.out.println("The Options in the Dropdown are: " + dropdown_list.size());

              // Condition to get the WebElement for list
              for(int i=0; i<dropdown_list.size(); i++)
              {
                   // Printing All the options from the dropdown
                   System.out.println(dropdown_list.get(i).getText());
            }                                                                                       
      }
}

Output
The Options in the Dropdown are: 29
Simple Form Demo
Checkbox Demo
Radio Buttons Demo
Select Dropdown List
Input Form Submit
Ajax Form Submit
JQuery Select dropdown

Here,

1) Open a web page – https://www.seleniumeasy.com/test/
2) Click on BootStrap DropDown – Input Forms by using (“//*[@id=’navbar-brand-centered’]/ul[1]/li[1]/a”
3) Get the all WebElements inside the dropdown in List  by using
(“//ul[contains(@class,’dropdown-menu’)]//li//a”)
4) Print all the options of DropDown using dropdown_list.get(i).getText()

How to select a particular option from Bootstrap dropdown

In the below example, there is a Bootstrap dropdown. I want to
Check if an element – Checkbox Demo is present in the dropdown or not.
If Yes, click on that option.

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class BootStrapDemo {
        public static void main(String[] args) {

System.setProperty("webdriver.chrome.driver","C:\\Users\\SingVi04\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

          WebDriver driver= new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.seleniumeasy.com/test/");
          driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
 
                // Clicking on Bootstrap Dropdown
               driver.findElement(By.xpath("//*[@id='navbar-brand-centered']/ul[1]/li[1]/a")).click(); 
 
                // Get the all WebElements inside the dropdown in List  
               List dropdown_list =  driver.findElements(By.xpath("//ul[contains(@class,'dropdown-menu')]//li//a"));
 
              // Printing the amount of WebElements inside the list
               System.out.println("The Options in the Dropdown are: " + dropdown_list.size());
 
              // Condition to get the WebElement for list
              for(int i=0; i<dropdown_list.size(); i++)
              {
                   // Printing All the options from the dropdown
                   System.out.println(dropdown_list.get(i).getText());                 
// Checking the condition whether option in text "Checkbox Demo" is coming
 
          if(dropdown_list.get(i).getText().contains("Checkbox Demo"))
            {
                 // Clicking if text "Checkbox Demo" is there
                 dropdown_list.get(i).click();
              // Breaking the condition if the condition get satisfied
                 break;
          }
       }
   driver.quit();            
  }
}

OutPut
The Options in the Dropdown are: 29
Simple Form Demo
Checkbox Demo

This program can be re-written by using Enhanced for loop instead of For loop.

getText() can be replaced by getAttribute(“innerHTML”)

import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class BootStrapDemo {
        public static void main(String[] args) {
 System.setProperty("webdriver.chrome.driver","C:\\Users\\SingVi04\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

          WebDriver driver= new ChromeDriver();
          driver.manage().window().maximize();
          driver.get("https://www.seleniumeasy.com/test/");
          driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
 
                // Clicking on Bootstrap Dropdown
               driver.findElement(By.xpath("//*[@id='navbar-brand-centered']/ul[1]/li[1]/a")).click(); 
 
                // Get the all WebElements inside the dropdown in List  
               List dropdown_list =  driver.findElements(By.xpath("//ul[contains(@class,'dropdown-menu')]//li//a"));
 
              // Printing the amount of WebElements inside the list
               System.out.println("The Options in the Dropdown are: " + dropdown_list.size());
 
              // Condition to get the WebElement using Enhanced For loop
 
               for(WebElement element:dropdown_list)
 
              {
                   // Printing All the options from the dropdown
                   System.out.println(element.getAttribute("innerHTML"));             
 
                  // Checking the condition whether option in text "Checkbox Demo" is coming
       if(element.getAttribute("innerHTML").contains("Checkbox Demo")) 
            {
                 // Clicking if text "Checkbox Demo" is there
                 element.click();
              // Breaking the condition if the condition get satisfied
                 break;
          }
       }
   driver.quit();            
  }
}

How to handle Dynamic Web Tables using Selenium WebDriver

 

In this blog we will discuss about automating dynamic web tables using Selenium WebDriver. Table is also a type of Web Element like checkbox, Radio Button, etc.

Table is a kind of web element, which is displayed, with the help of  tag in conjunction with the <tr> tag defines the row of the table and <th> tag tag for headings which defines heading of the table.

There are 2 types of HTML table

1. Static Table – Where number of rows and columns are fixed.
2. Dynamic Table – Where number of rows and columns are not fixed.

Below table is a Dynamic table. Based on input Assignee filter, the number of rows get altered. 

How to locate Web Table Elements

1) Open Chrome browser and go to – https://www.seleniumeasy.com/test/table-search-filter-demo.html

2) Take a note that “Element” tab is the one which displays all the HTML properties belonging to the current web page. Navigate to the “Element” tab if it is not opened by default on the launch.

3) In the screenshot, we can see the HTML code of Task web element of the table. Right click on this text and select Copy and then again click where will see options like – Copy Selector, Copy XPath, Copy full XPath.

Copy XPath
//*[@id="task-table"]/thead/tr/th[2]

Copy full XPath
/html/body/div[2]/div/div[2]/div[1]/div/table/thead/tr/th[2]

Copy Selector
#task-table > thead > tr > th:nth-child(2)

How to find full XPath of Web Table

If we divide this xpath  – /html/body/div[2]/div/div[2]/div[1]/div/table/thead/tr/th[2] into three different parts it will be like this

·         Part 1 – Location of the table in the webpage /html/body/div[2]/div/div[2]/div[1]/div />

·         Part 2 – Table body (data) starts from here

·         Part 3 – It says table row 1 and table head 2

In the below image, we can see that the highlighted tags are used to create absolute XPath – html/body/div[2]/div/div[2]/div[1]/div/table/thead/tr/th[2]

If we want to create a relative XPath, then the below image shows that find a unique identifier like id=’task-table’ and then create Relative XPath

//*[@id="task-table"]/thead/tr/th[2]

Below is an example, which will show how to fetch a particular cell data in Dynamic Web Table. We want to fetch the data from row 5 and column 3 and row 6  column 2. We have used Relative XPath as well as absolute XPath to fetch the data.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class DynamicTable_RowData {
        public static void main(String[] args) {
 System.setProperty("webdriver.chrome.driver","C:\\Users\\Vibha\\Desktop\\Drivers\\chromedriver_win32\\chromedriver.exe");

        WebDriver driver = new ChromeDriver();      
        driver.manage().window().maximize();
        driver.get("https://www.seleniumeasy.com/test/table-search-filter-demo.html");           
        
String CellData1 = driver.findElement(By.xpath("//*[@id='task-table']/tbody/tr[5]/td[3]")).getText();
        System.out.println("Data in 5th row and 3rd column :"+CellData1);

           String CellData2 = driver.findElement(By.xpath("/html/body/div[2]/div/div[2]/div[1]/div/table/tbody/tr[6]/td[2]")).getText();
        System.out.println("Data in 6th row and 2nd column :"+CellData2);
        driver.close();
        }
}

Output
Data in 5th row and 3rd column :Holden Charles
Data in 6th row and 2nd column :Browser Issues

How to create first Selenium WebDriver Script using Java

We assume here that Selenium WebDriver is download and installed with Eclipse. If not, please refer this link

In this tutorial, we will see how to create a simple Selenium WebDriver script using JAVA. The most important thing is that JAVA, Eclipse and Selenium WebDriver are already install in the machine. If not, then please refer the link – How to Download & Install Selenium WebDriver.

To create our first Selenium WebDriver Script, we have to create a Java Project, Package and Class in Eclipse.

1. Create a Java Project “AutomationSuite” – Click File ->New ->Other ->Project ->Java Project. Click Next.

  • Provide Package Name – here I have provided AutomationSuite 
  • JRE – Use an execution environment JRE: JavaSE-1.8 (This is the version of Java on your machine)
  • Project Layout – Create separate folders for source and class files

ii. Create a package “SeleniumTutorial” – Right click Java Project (AutomationSuite) ->Click File ->New ->Package

iii. Create a Java Class “FirstProgram” – Right click Java Package (SeleniumTutorial) ->Click File ->New ->Class

  • Name: Name of the class (FirstProgram)
  • Modifiers – Public
  • Which method stubs would you like to create – public static void main(String[] args) and click Finish

Above displayed image explains the structure of Project in Eclipse.

Add Selenium Jar files to the Java Project


1.  Right click on AutomationSuite and click on Properties.

2.  Click on Java Build Path. Select Libraries. Click on – Add External JARs

3.  Go to the path where Selenium WebDriver JAR folder was downloaded and select 2 JAR files – client-combined-3.141.59 and client-combined-3.141.59-sources and click on Open button.

4. Similarly, go to Lib folder of Selenium file and select the entire JAR present there

5. To verify that the JAR’s are added or not, click on Referenced Libraries and will see all these JARs are present here. For more details, refer the link

Scenario:


To open appropriate URL and verify the title of the home page
Steps:
i. Open Chrome browser
ii. Go to the specified URL – http://www.google.com
iii. Verify the title and print the output of the title
iv. Close the Chrome browser

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.chrome.ChromeDriver;
 
public class FirstProgram {
       
     public static void main(String[] args) {
               
 System.setProperty("webdriver.chrome.driver","C:\\Users\\vibha\\Downloads\\Drivers\\chromedriver_win32\\chromedriver.exe"");

         WebDriver driver = new ChromeDriver();
         driver.manage().timeouts().implicitlyWait(40, TimeUnit.SECONDS);
         driver.get("https://www.google.com/");
         String PageTiltle = driver.getTitle();
         System.out.println("Page Title :"+PageTiltle);
         driver.close();
     }
}

To run this program, go to Run->Run or Green Icon shown below