whatsapp

Selenium Tutorial for Beginners: Overall view into the Tool

Selenium

Monday April 1, 2019

Everybody knows about the impeccable selenium! The ultimate tool for testing web applications! The core components of selenium are, Selenium IDE, Selenium RC, web driver and Selenium Grid. Selenium IDE is based on record and play mechanism.

What makes Selenium better?

You don’t need to code anything in Selenium and with this; any beginner will be able to record and play the simplest web application scripts.

Usually, Selenium RC needs a server to be up and running for sending commands to the browser. It is used for cross-browser testing and you can write the code in any language.

Selenium Web Driver is a better version of IDE and RC. It directly sends commands to the browser without the need of a server to be up and running.

Different languages can be used for coding the scripts like Java, C#, PHP, Python, Perl and Ruby. Selenium Grid is used for parallel testing in multiple browsers and environments. It used the hub and node concept where hub acts as a source of Selenium commands and each node is connected to it.

Now, here we will discuss Selenium WebDriver. How a beginner can start learning Selenium WebDriver and how he can excel in it.

Now, first, we will look at the steps we need to follow to download Selenium WebDriver in your machine.

Ways to download and install Selenium WebDriver

  • You should have Java installed in your machine. This is the pre-requisite for Selenium WebDriver to work.
  • You can visit the page: http://seleniumhq.org/download/ and download the client drivers and language bindings. You have the select binding for Java.
  • This download will be named – selenium-2.25.0.zip.
  • Now, you can import all the Jars in Eclipse. You have to right click on the project and import jar files by selecting all the downloaded jar files. For this, you can click on the Libraries tab and then click on “Add External JARs”.

Now Let’s look the First Selenium WebDriver Script

Let’s take an example of the first Selenium Script which we would create using Selenium basic methods.

Let’s first look at the script in detail. In this script, we will do the following test steps.

  • Go to home page of the test application
  • Verify the title of the page
  • Do a comparison of the result.
  • Close the browser after the script is done.

package projectSelenium;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class seleniumTest {

public static void main(String[] args) {

System.setProperty(“webdriver.chrome.driver”,”C:\\chromeDriver.exe”);

WebDriver driver = new ChromeDriver();

String baseUrl = “https://google.com”;

String expectedTitle = “Google”;

String actualTitle = “”;

        // launch Fire fox and direct it to the Base URL

driver.get(baseUrl);

        // get the actual value of the title

actualTitle = driver.getTitle();

/*

* compare the actual title of the page with the expected one and print

* the result as “Passed” or “Failed”

*/

if (actualTitle.contentEquals(expectedTitle)){

System.out.println(“Test Passed!”);

} else {

System.out.println(“Test Failed”);

}

driver.close();

}

}

Things to look at the above code:

  • In the first two lines, we have imported two packages. You have to import – org.openqa.selenium and org.openqa.selenium.firefox.FirefoxDriver.
  • The most important step is to instantiate the browser. This is done by line

WebDriver driver = new ChromeDriver();

//This is done to invoke a chrome browser.

You can invoke a FireFox browser by following line of code

WebDriver driver = new FirefoxDriver();

You can invoke an IE browser by following line of code:

WebDriver driver = new InternetExplorerDriver ();

Also, while invoking a browser you have to pass the path of the executable file. You can do it by following line of code:

System.setProperty(“webdriver.chrome.driver”,”Path of chrome driver”);

System.setproperty(“webdriver.ie.driver”,”Path of ie driver”);

  • Get() method is used to enter a url in a browser.
  • getTitle() method of selenium webdriver is used to fetch the title of a web page.
  • Now, we have to compare the expected title with the actual title.

If(expectedTitle.equals(actualTitle))

{

System.out.println(“TEST PASSED”):

}

  • For terminating the browser, close() method is used. Driver.close() closes the active browser window. If you want to close all the opened browser windows by selenium webdriver then you can use driver.quit().
  • You can run this test by right clicking on the program and then select as “Run As” as “Java Application”.
  • Next thing which is of utmost important while writing a test script is to identify webElements which will be explained in detail in the below section.

Locating WebElements

Locating webelements is very easy. Various selectors are available for that process. findElements is one such2 in which selenium webdriver is used for locating a webelement and then, you can perform an action on that.

Know More: Selenium Automation Testing With Cucumber Integration

Let’s see some of the methods by which you can identify webelement on a web page.

  • className – It will locate web element based on the class attribute. Eg: By.className(“abc”);
  • cssSelector – used to locate web element based on css selector engine. Eg:- By.cssSelector(“#abc”);
  • id – If some web element has id attribute, then you can directly identify the web element using id tag. Eg:- By.id(“abc”);
  • linkText – It will find a link element by text mentioned by you in the test script. By.linkText(“Login”);
  • name – If any web element has name attached to it then you can identify it using name attribute. Eg: By.name(“name”);
  • partialText – It will find a link element by text containing the text mentioned by you in the test script. By.partialText(“abc”);
  • tagName – It will locate all elements which will have this tag.
  • xpath – It is the most used locator in a selenium test script. It will identify the element using html path. It can be relative or absolute. Absolute xpath traverses the path of the web element by root and relative takes the reference of any web element and then traverse to that specified web element. It is better to refer an element by relative xpath rather than absolute xpath.

Basic Actions on a web element

You can click on a web element by using click() method of selenium web driver. You can locate a webelement and then perform an action on it.

Eg: driver.findElement(By.xpath(“”)).click();

Also, you can send keys to a particular web element by using sendKeys() method of selenium web driver. You can locate a web element and then you can enter some text in it using sendKeys() method.

Eg: driver.findElement(By.xpath(“”)).sendKeys(“name”);

Also, there are other actions which you can perform on a web element by using action class.

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

Actions actions = new Actions(Driver);

Actions.moveToElement(wb).build(). Perform ();

You can even switch to alert boxes which come when you click on some webelement. You can do it by switchTo().alert() method.

Eg code:

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

Wb.click();

Driver.switchTo().alert();

Now, you will be able to access the alert box. You can retrieve the message displayed in the text box by getting the text from it.

String alertMessage = driver.switchTo().alert().getText();

Also, you can accept the alert box by function accept(). You can see the sample code as below:

Driver.switchTo().alert().accept();

You can even check conditional operations on a web element.

Also, check whether a web element is enabled or not. If it will be enabled then you can do some operation on it.

Apart from all these, you can check if some web element is displayed or not. In the case of radio buttons, you can check if the radio button is selected or not. You can do these checks by – isEnabled(), isSelected() and isDisplayed() option.

Waits in Selenium Web Driver

If you want some step to get completed before any other step then you have to wait for the prior step to get completed. In manual testing, it is very easy to achieve but in automation testing, it is bit tedious and you have to wait for the previous step to get completed or a condition to be fulfilled before moving onwards to the next step.

This can be achieved by adding waits in between. There are two types of wait- explicit and implicit wait. If you are expecting a particular condition to be fulfilled before moving to the next step,

Another feature is that you can use explicit wait while if you just want a universal wait, then you can go ahead to use implicit wait. The implicit wait is used to set the default time out for the whole script.

A perfect automation script is made by adding both type of waits – Explicit and Implicit. You have to judiciously use both types of waits to make an efficient test case.

Know More : Top 50 Selenium Interview Questions and Answers

Explicit Wait

Syntax of Explicit Wait:

WebDriverWait wait = new WebDriverWait(WebDriverRefrence,TimeOut);

wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(“”));

Expected Condition can be used with so many conditions. Some conditions which can be used with it are:

  • alertIsPresent()
  • elementSelectionStateToBe()
  • elementToBeClickable()
  • elementToBeSelected()
  • frameToBeAvaliableAndSwitchToIt()
  • invisibilityOfTheElementLocated()
  • invisibilityOfElementWithText()
  • presenceOfAllElementsLocatedBy()
  • presenceOfElementLocated()
  • textToBePresentInElement()
  • textToBePresentInElementLocated()
  • textToBePresentInElementValue()
  • titleIs()
  • titleContains()
  • visibilityOf()
  • visibilityOfAllElements()
  • visibilityOfAllElementsLocatedBy()
  • visibilityOfElementLocated()

Implicit Wait

Syntax of Implicit Wait:

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

For this, you have to import a package into your code. The package name is java.util.concurrent.TimeUnit;

Conclusion

If you will go through the Selenium Tutorial for Beginners above, you will get to know that how a simple selenium script is made for a beginner. Practice and be perfect! Follow our intermediate course of more understanding. All the best!!

Mail

Hire a Tester

WhatsApp

Call Us

Testbytes