15 Top Selenium WebDriver Commands For Test Automation

The use of selenium webdriver helps in testing every aspect of the web application. It is an open-source website automation tool that is used mostly by the automation testers.
With the help of Selenium Webdriver, applications are tested to see whether they are working as expected or not.
To ease your work we will provide you with some basic commands list which you can use in selenium webdriver. Using these commands it will make things easier for you.
Basic Commands List for Selenium Web driver
1. To Select Multiple Items in a Drop down
2. get() commands
3. Use of linkText() and partialLinkText() command
4. Form Submission Command
5. Using quit() and close() Commands
6. Command to handle Multiple Frames
7. findElements(By,by) and click() Command
8. isEnabled() Command
9. Using findElements(By, by) with sendKeys() Command
10. Using findElements(By, by) with getText() Command
11. Using findElements(By, by) with size() Command
12. select() Command
13. navigate() Command
14. getScreenshotAs() Command
15. pageLoadTimeout(time,unit) Command
1. To Select Multiple Items in a Drop down
There are two options which you can use to select items in a drop-down i.e. single select dropdown and multi-select drop-down. Single select dropdown allows the user to select only one item from the drop-down whereas Multiple-select dropdown allows the user to select multiple items from the dropdown list.
You can use this code to generate a list in which you can select multiple items in a drop-down.
<select name=”Country” multiple size=”6”>
<option value=”India”>India</option>
<option value=”Belgium”>Belgium</option>
<option value=”England”>England</option>
<option value=”France”>France</option>
<option value=”Italy”>Italy</option>
</select>
When a form is submitted the value has to be sent to a server, this value is sent specifically by the value attribute. Content will pass as a value if the value attribute is not specified.
Syntax- <option value=”value”> where ‘value’ is the value which has to be sent o the server.
2. get() commands

  • get(): This command is used to launch a new browser with the specific URL in the browser. This command uses a single string type which is generally the URL of the application under test. The syntax of the command can be given as driver.get(http://facebook.com)
  • getCurrentUrl(): The command is used to fetch the current URL of the webpage which user is accessing. It returns a string value and doesn’t need any external parameters. The syntax of the command is given as driver.getCurrentURL();
  • getTitle(): This command fetches the title of the webpage which user is currently using. This command doesn’t require any external parameters and returns a string value. If the webpage doesn’t have any title it will return a null string. The syntax of the command is given as String new = driver.getTitle();
  • getAttribute(): This command is used to fetch the value of the specific attribute. This command uses a string which refers to an attribute whose value we want to know and returns a string value. The syntax of the command is given as driver.findElements(By.name(“x”)).getAttribute(“value”);
  • getText(): This command is used fetch the inner text of the element including sub-elements. This command returns a string value and doesn’t need any external parameters. This command is often used for verification or errors in the message or content in the web pages. The syntax of the command is given as String new = driver.findElements(By.name(“Inner_text”)).getText();
  • getClass(): This command is used to fetch the class object. The syntax of the command is given as driver.getClass();
  • getPageSource(): This command is used to fetch the page of the web page which user is currently working on. This command returns a string value and doesn’t require any other parameters. The syntax of the command is given as String new = driver.getPageSource();


3. Use of linkText() and partialLinkText() command
These commands are used to access the hyperlinks which are available on a webpage. By using these commands user is redirected to another page.
Let us consider there are two links mentioned in the webpage Google and Yahoo.

  • linkText(): Twitter and Yahoo links can be accessed using the command driver.findElements(By.linkText(“Twitter”)).click();

driver.findElements(By.linkText(“Yahoo”)).click();
This command finds the element by using linkText() and then click on that link. The user is then redirected to the page followed by the link.

  • partialLinkText(): Links can be accessed by using command driver.findElements(By.partialLinkText(“Twitt”)).click();

driver.findElements(By.partialLinkText(“Yaho”)).click();
This command finds the element partially by using partialLinkText() and then clicks on it.
4. Form Submission Command
Almost every webpage contain forms which have to be filled by the user. There are various types of forms like login, registration, file upload or new signup etc. While testing of the website the command submit() is used. It triggers the submit button without clicking on the submit button. The code for the form submission is as follows:
//First Name
<input type=”text” name=”FirstName”>
//Last Name
<inpur type=”text” name=”LastName”>
//Email ID
<input type=”text” name=”EmailID”>
//Mobile Number
<input type=”text” name=”MobileNo”>
<input type=”submit” value=”submit”>
5. Using quit() and close() Commands
These commands are used to close the web pages which are currently used by the user.

  • quit(): The quit() command is used to close down all the web pages in the web browser. All the web pages which are being opened by the users are closes down instantly. The syntax of the command is given as driver.quit(); This command doesn’t need any other parameters and doesn’t return any value.
  • close(): the close() command is used to close down the current webpage which is being opened by the user. This command only closes a single webpage unlike quit(). This command doesn’t need any other parameters and doesn’t return any value. The syntax of the command is given as driver.close();

6. Command to handle Multiple Frames
There are scenarios where the users have to work on various frames and iframes. The script tester verifies the working of the frames through script code. The illustration of the code is given below where there are different frames in the webpage.
<html>
<head>
<title>Window handle</title>
</head>
<body>
<div>
<iframe id=”FirstFrame”>
<iframe id=”SecondFrame”>
<input type=”text” id=”Name”>FirstName</input>
<input type=”text” id=”Name”>LastName</input>
</iframe>
<button id=”Submit”>Submit</button>
</iframe>
</div>
</body>
</html>
In this HTML code, two iframes are present. Thus to access the second frame user has to navigate through the first frame. Only by dealing first frame user are allowed to navigate to the second frame. It is impossible for the user to access directly the second frame without using the first frame.

  • Frame(index): swtichTo().frame(0);
  • Frame(frame name):switchTo().frame(Frame name”);
  • Frame(Web element):switchTo().defaultContent();

These commands can be used by the user to return back to the main window.

  • Selecting iframe by ID: switchTo().frame(“Frame ID”);

7. findElements(By,by) and click() Command
This command is used by the user to search or locate the first element on the webpage. The parameters which are used in the syntax fetch the element on the current working page. Click, submit or another type of actions are mainly used by this command. The syntax of this command is given as driver.findElements(By.Name(”login”)).click();

Also Read : Automation Test For Website and Web Apps Using Selenium

This command is used to locate and searches the first element of the web page with the name ”login” and then clicks on it.
8. isEnabled() Command
This command is used to check whether the element in the selenium webdriver is enabled or not. The syntax of this command is given as
Boolean check = driver.findElements(By.xpath(“Name”)).isEnabled();
This command finds the element and checks whether the element is enabled or disabled.
9. Using findElements(By, by) with sendKeys() Command
This command is typically used for filling in forms. The general syntax for this command is given as driver.findElements(By.name(“FirstName”)).sendkeys(“Tony”);
This command will search for the first name field and then enter the value “Tony” in it.
10. Using findElements(By, by) with getText() Command
With the help of the getText() command, it will get the inner element of the webpage. By using this command we can store the value of the element into the string object. The syntax for this command can be given as
String new = driver.findElements(By.TagName(“NewFile”)).getText();
This command will look for the field name “new file” then take its inner file and stores it into the string name “new”.
11. Using findElements(By, by) with size() Command
With the help of this command, we can verify whether the element which we are looking for is present in the webpage or not. The syntax for this command can be given as
Boolean check = driver.findElements(By.xpath(“FileName”)).size()! = 0;
It will check the element whether it is available or not. The Boolean will set the “Check” to TRUE or FALSE respectively.
12. select() Command
This command is used to select or deselect the values from the list. To select a value we can use different commands like selectByVisbibleText(), selectByValue() or selectByIndex() according to the situations. The syntax for these commands can be given as
Newfile.selectByVisibleText(“Google”);
Newfile.selectByIndex(“Google”);
Newfile.selectByValue(“Google”);
These syntaxes are used for selection only. We can also deselect the values from the list by the following syntax.
Newfile.deselectByVisibleText(“Google”);
Newfile.deselectByIndex(“Google”);
Newfile.deselectByValue(“Google”);
“New file” is the element containing the values which has to be selected.

13. navigate() Command
This command is used to navigate between different URLs in the webpage. By using this command we can navigate back and forth in the current webpage. The syntax for the command can be given as
driver.navigate().to(“http://www.Google.com”);
driver.navigate().back();
driver.navigate().forward();
This command will help the user to navigate http://www.Google.com, navigate back and navigate forward.
14. getScreenshotAs() Command
This command will enable the user to screenshot the entire page in the selenium webdriver. The syntax of the command is given as
File screenshot = ((TakeScreenshot)driver).getScreenshotAs(outputType.FILE);
FileUtils.copyFile(screenshot, new File(“c:\\ss.jpeg”));
This command will take the screenshot and will save the file in C drive as ss.jpeg
15. pageLoadTimeout(time,unit) Command
When the servers are down or there is an issue in the network, the page often takes more time to load. This might cause an error in the program. To avoid this situation, a command is used to set a wait time. The syntax can be given as
driver.manager().timeouts().pageLoadTimeout(200, SECONDS);
By using this command 200 seconds will be enabled. It will wait 200 seconds for a page to load.
16. Switch to window
driver.switchTo().window(“windowName”);
17. Find the location of the element
WebElement name = driver.findElement(By.id(“Name”));
Point point = name.getLocation();
String strLine = System.getProperty(“line.separator”);
System.out.println(“X cordinate# ” + point.x + strLine + “Y cordinate# ” + point.y);
19. Find the value of CSS property
WebElement name = driver.findElement(By.id(“Name”));
String strAlign = name.getCssValue(“text-align”);
20. Check the visibility of web command
WebElement user = driver.findElement(By.id(“User”));
boolean is_displayed = user.isDisplayed();
//Or write the code in the below style.
boolean is_displayed = driver.findElement(By.id(“User”)).isDisplayed();
We genuinely hope that this selenium webcommands is of great use to you

Also Read : 10 Best Automation Testing Tools For 2018

Selenium Tutorial For Beginners [Step by Step]

Everybody knows about the impeccable selenium! The ultimate tool for testing web applications! for you to learn in detail about how to carry out automation testing, we have written an extensive Selenium tutorial just for you!
This blog comprises of three part,
1. Selenium Tutorial For Beginners
2. Selenium Intermediate Level Tutorial
3. Selenium Advanced level Tutorial

Selenium Tutorial For Beginners

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 Web Driver 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 Web Driver 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 the 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 web driver 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 web Elements which will be explained in detail in the below section.

Locating Web Elements

Locating web elements is very easy. Various selectors are available for that process. find Elements is one such 2 in which selenium webdriver is used for locating a web element 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 web element 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 web element 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 send Keys() 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

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 on wards 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;

Selenium Intermediate Level Tutorial

Through the section Selenium Tutorial for Beginners, We gave you the basic info that you need to know about the tool. Now let’s go further and learn much more about this impeccable web app testing tool.
How to upload a file in Selenium test cases?
To upload a file, first, you have to identify the element on which you have to upload your file. There you can directly use sendKeys() function of selenium web driver. You can pass the path of the location in sendKeys. In this way, you will be able to upload a file using selenium web driver.

public static void main(String[] args) {
System.setProperty(“webdriver.gecko.driver”,”path of gecko driver”);
String baseUrl = “http://www.google.com /upload/”;
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement element = driver.findElement(By.id(“id of element”));
uploadElement.sendKeys(“C:\\newhtml.html”);
//Here,  above you have to pass the path of the file where your file is located.
// Then you can click the upload file link
driver.findElement(By.xpath(“”)).click();
}
How to use a web table in selenium script
You have to access a web table and the elements present in the table. You can get it by making an xpath. Suppose you have had1 0a table with four blocks.
selenium intermediate tutorial
The first thing which you have to do is to find the XPath of the web element in this web table. Let’s say you want to get to the third element in the above web element.
The coding of the above web table is as below:

Selenium Intermediate Level TutorialSelenium Intermediate Level Tutorial
Now, you can analyze that first there is a table and then there is a tbody. In that tbody there are two rows. One row is having two tables. The first row is having two cells – First and Second. The second row is having two cells – Third and Fourth.
Our goal is to reach to the third cell. Let’s try to make the XPath of it.
The XPath of it will be //table/tbody/tr[2]/td[1]
So, the table is the parent node from which we will iterate to go the third element. From there, we will go to the tbody section and then the second row. From there we will get the first column.
Let’s write a script to get the text out of it.
public static void main(String[] args) {
String url = “http://testsite.com/test/write-xpath-table.html”;
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
String txtWebelement = driver.findElement( By.xpath(“//table/tbody/tr[2]/td[1]”).getText();
System.out.println(txtWebelement);
driver.close();
}
}
Let’s take an example of a nested web table. You have to then analyze it carefully and get the XPath of it. Let’s look at the example below to get more information on it.
Selenium Intermediate Level Tutorial:
So, if you want to access the web element which is having text 10-11-12 then you can do it by traversing from the table and then iterating through the rows and columns to reach there.
Xpath would be: //table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]
public static void main(String[] args) {
String url = “http://testsite.com/test/write-xpath-table.html”;
WebDriver driver = new FirefoxDriver();
driver.get(baseUrl);
String txtWebelement = driver.findElement( By.xpath(“//table/tbody/tr[2]/td[2]/table/tbody/tr[2]/td[2]
”)getText();
System.out.println(txtWebelement);
driver.close();
}
}
This way, you can iterate through the rows and columns to reach to a specific cell from a web table.
Now, one of the most important concepts in selenium which will help you in many cases when you won’t be retrieving any text from a web element or to enable a web element to get the text or to perform any action on it.
Let’s talk about JavaScript Executor in detail. It is an interface which helps to execute javascript.
JavaScript Executor
Sometimes you are not able to click on a web element using click() function. You can then use javascript executor to execute click function on a web element. Let’s have a look at the code.
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
You can now click on a webelement using below command.
WebElement button = driver.findElement(By.xpath(“”));
Js.executeScript(“arguments[0].click();”,button);
Also, if send keys isn’t working. You can make use of java script executor to send keys. Let’s look at the example below.
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“document.getElementById(‘id’).value=”value;”);
You can even make use of java script executor to refresh a web page. You can do it by following command:
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
Sometimes, getText() doesn’t work and then you have to make use of java script executor to get text of a web element. You can do it by following line of code:
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript(“history.go(0)”);
Sysout(js.executeScript(“return document.documentElement.innerText;”).toString());
You can even get the title and URL of a web page using java script executor. The procedure is very simple. Let’s have a look at the following lines of code.
WebDriver driver= new FirefoxDriver();
// JavascriptExecutor interfaceobject creation by type casting driver object
JavascriptExecutor js = (JavascriptExecutor)driver;
System.out.println(js.executeScript(“return document.title;”).toString());
System.out.println(js.executeScript(“return document.URL;”).toString());
Desired Capabilities Concept in selenium web driver
You can make the set of configurations on which you want a particular test script to run. You can pass browser name, version to specify the type of environment on which you want a test case to run.
Let’s see some of the capabilities which you can set in a test case for IE browser.
//it is used to define IE capability
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(CapabilityType.BROWSER_NAME, “IE”);
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
In the above capability, we have passed the capability browser name and we have ignored the security domain.
After setting the capabilities you can pass the capabilities to the web driver instance so that it executes the test on a particular configuration.
Let’s have a look at the complete set of code.
public static void main(String[] args) {
//it is used to define IE capability
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(CapabilityType.BROWSER_NAME, “IE”);
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS,true);
System.setProperty(“webdriver.ie.driver”, “path of executable”);
WebDriver driver = new InternetExplorerDriver(capabilities);
driver.get(“http://gmail.com”);
driver.quit();
}
Handling a drop down in selenium web driver
You have to first import following packages: org.openqa.selenium.support.ui.Select.
First, you have to identify from DOM whether the dropdown is of select type or not. If it is of select type then you have to go for the below steps.
Then, you have to uniquely identify the select tag. You have to first make the object of Select class and pass the element for which you have to choose the options from the drop-down.
Select dropdown = new Select(driver.findElement(By.xpath(“”)));
Now, there are three main methods which you have to use to select any element from this select object.

  1. selectByVisibleText
  2. selectByIndex
  3. selectByValue

You can either select any element from this drop-down by matching the visible text with that of the text passed by you. You can also select any web element from the drop-down using an index. Last option is to select by value tag.
Also, there are some more functions which are available. Some of them are selectAll() and deselectAll() too select and deselect all the elements when more than one element can be selected.
But, if the dropdown is not of select type then you can’t go for the conventional method. You have to follow another method. You have to uniquely identify the web element on which you have to select a dropdown option. You can identify it and the sendKeys() function of selenium web driver to send keys to the uniquely identified dropdown.
WebElement dropdown = driver.findElement(By.xpath(“”));
Dropdown.sendKeys(“value to be selected”);
How to select the checkbox and radio button is selenium
Sometimes, you come across situations where you have to select checkboxes and radio buttons. You can do it easily with selenium web driver. You just have to use click() function of web driver to click on checkbox and radio button. You can even check of the web element is selected or not.
.isSelected() checks if any web element is selected or not.
It gives false if the web element is not selected and it gives true if the web element is selected.
This way, you can handle radio buttons and checkboxes in a selenium script.

Selenium Advanced level Tutorial

Now, you know almost the stuff which is required for selenium intermediate and beginner level. Now, you are proficient enough to deal with all the advanced level of selenium web driver. You can then practice those and while you are done with those, you can move forward to the advanced level of course.
Let’s see what lies ahead and what can give you an edge in your interviews. You can look at this advanced course so that you can be ahead of all the candidates who just know the basic and intermediate selenium course. Let’s have a look at Selenium Advanced level Tutorial

Selenium Grid


Selenium Grid is issued for running various tests on different browsers, operating systems, and machines in parallel. It used a hub and node concept. You don’t want test cases to run on a single machine. You have your machine as a hub and various systems on which test cases will be distributed. You call those machines as nodes.
The hub is the central point and there should be only one hub in a system. This hub is your machine from which you want to distribute the test cases among all the clients.
This is the machine on which test cases will run and those will be executed on the nodes. There can be more than one node. Nodes can have different configurations with different platforms and browsers.
Let’s see how you can establish a selenium grid in your machine.
You can download the selenium grid server from the official site. You can place Selenium server.jar in a hard drive. You have to place it in all nodes and hub c drive.
Open the command prompt in your hub and then, go to C directory. There you have to fire the below command java -jar selenium-server-standalone-2.30.0.jar -role hub
Now, if you want to check if the selenium grid server is running on localhost that is 4040 port or not. You can visit the local host on your browser.
You have to then go to C directory of the node and open command prompt in it. Also, when you have made the selenium grid server up in the hub, you have to note down the IP address and port.
java -Dwebdriver.gecko.driver=”C:\geckodriver.exe” -jar selenium-server-standalone-3.4.0.jar -role webdriver -hub ip address of hub -port port number of hub
When you fire the above command, again go to hub browser and the port number 4040. Refresh the page and you will see IP address which will be linked to the hub.
Now, you have set up machines with different configurations. But how would the hub know which test case would be run on which node.
This will be done by desired capabilities which will tell that this test script would run on a particular set of configuration.
One can do it using below source code:
This way, you will be able to distribute the test cases across different machines and browsers. You will be able to do parallel testing using Selenium Grid.

Maven and Jenkins Integration with Selenium


Maven is a build management tool which is used to make the build process easy. Maven avoids hard coding of jars and you can easily share the project structure across the team using artifact and version id.
Every team member would be at the same page. You can make a maven project by going to File – New – Other – Maven project. You have to then specify the artifact id and then version id. You will be prompted to select a template. For starting, select a quik start template.
You will get a folder structure where you will be having two folders – src/main/java and src/main/test. In java folder, you will maintain all other stuff except tests while in test folder you will maintain all the test cases.
You will be having pom.xml file where you have to define all the dependencies so that it can download from the maven repository and place them in ./m2 repository in your local project structure.
You can get the dependency from the maven official site and then place in pom.xml. It will download all the required jars.
Also, Jenkins issued for continuous integration of the latest build with the production environment. Whenever a developer will fire the latest build then the smoke test will start running on that build.
If the build gets passed then it can be deployed to the production else the developer and tester would get a notification about the failed build. It makes the delivery cycle very fast.
Also, you can do it by downloading Jenkins war file and then running it so that Jenkins server will be up and running on port number 4040.

After doing that you can install all the necessary plug-ins. You can then create a new item and does the post-build actions.
Also, you can pass the path of git repository from which it will fetch the latest build. If you are using a local server then you pass the path of pom.xml from the system.
You can even set nightly runs with Jenkins, You have to specify the time when you want your test to run. They will run and you will get the reports on the Jenkins server the next morning. Isn’t it time-saving?

Database Testing using Selenium WebDriver

Integrating Selenium tests to the database is so easy in the latest version of the tool. You have to make use of JDBC library for database connections. It allows connection of Java and databases. First, make a connection to the database with the following command:

DriverManager.getConnection(URL, “userid”, “password” )
After doing that you can load the JDBC driver. You can do it by following lines of code:
Class.forName(“com.mysql.jdbc.Driver”);
Now, you have to send the query to the database. How will you do it? You can create an object of a statement class and then execute the query using the statement object.
Statement stmt = con.createStatement();
stmt.executeQuery(select *  from employee;);
Now, you can get the result in the result set. You can do it by following command:
ResultSet rs= stmt.executeQuery(query);
After doing all the operations, you can close the connection.
Con.close();
In this way, you can get the result set and then do all the validations on the result set.

How to take screenshots in selenium web driver

You should get the screenshot of the failed test cases so that you can get to know where exactly is the problem. This will help in better-debugging skills.

Let’s look at the steps involved in taking a screenshot:
TakesScreenshot scrShot =((TakesScreenshot)webdriver);
This step caste a driver instances to Takes Screenshot interface. Now, you have one method which is getting screenshots which will get the image file.
File SrcFile=scrShot.getScreenshotAs(OutputType.FILE);
Now, you have taken the screenshot but you have to place it somewhere. You can create some folder which will be used for storing all the screenshots captured during the execution.
You can do it by following the line of code:
FileUtils.copyFile(SrcFile, DestFile);
This is the way to capture screenshots. But if you want that only the screenshot is taken when a test case fails. You can use ITestListener.
It has various methods and one of the methods is onFailure() which will do the specified task when every there is any failure in a test case.
So you can put this code in that method so that whenever any test fails it will take the screenshot and place it in the folder specified by you.

How to drag and drop in a web page using Selenium Web driver

Now if you want o drag and drop something o a web page, you would be confused. It is very simple. You have to make use of Actions class which gives you a method dragAndDrop() which will drag and drop a web element from a source destination to the desired destination.
Actions actions = new Actions(driver);
Actions. dragAndDrop(Sourcelocator, Destinationlocator).build().perform();
Make sure that the source locator and destination locator have correct xpaths. In this way, you will be able to drag and drop any element on a web page.

How to do right click and double click on a web page

You can do a right-click on a web page using Actions class. Actions class provides a doubleClick method which allows to double click on a web element. You can do it by following lines of code:

Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id(“ID”));
actions.doubleClick(elementLocator).perform();
You have to do right-click in selenium using action class only. It is very easy. It provides a method – contextClick() and then right click on a web element.
Actions actions = new Actions(driver);
WebElement elementLocator = driver.findElement(By.id(“ID”));
actions.contextClick(elementLocator).perform();
This way, you will be able to right click and double click on a web element.
How to switch to an iFrame

iFrame is a web page which is embedded into another web page. Whenever you want to click on a web element, which is in another iframe. First, you have to switch to that iframe and then perform an action on it.
You can do switching by
Driver.switchTo().frame(index or name or id of iframe);
Conclusion
Before learning Selenium it’s better to have a thorough understanding of any object-oriented language. languages that Selenium support includes, Java, Perl, C#,  PHP, Ruby, and Python Currently.
We genuinely hope this tutorial has helped in understanding selenium better.

Get a eBook : Download PDF

Difference Between Selenium RC and Webdriver

Testing is an integral part of any product’s development. Therefore, it is important for every organization to have a stringent quality testing strategy and framework that helps it ensure the best quality of its products. While a number of software are already present in different frameworks in the market, Selenium is one of the most preferred one.
Difference Between Selenium RC and Webdriver
Selenium is defined as a portable software-testing framework that can be used for web applications. It can be used for authoring tests without the need to learn scripting language Selenium IDE and test domain-Selenese to write tests in a number of popular programming languages, including C#, Groovy, Java, Perl, PHP, Python, Ruby and Scala. These tests can used to execute against different-or latest web browsers.
A user can use selenium on Windows, Linux, and OS X platforms as well. It is an open-source software, released under the Apache 2.0 license and is available for free for downloading.

Selenium includes a number of components and each of these have a specific function to perform development of web application test automation. Some of the common components are Selenium IDE (integrated development environment), Selenium client API, Selenium RC (Remote Control), Selenium WebDriver and Selenium Grid.
Difference Between Selenium RC and Webdriver
 While it is true that Selenium WebDriver python test automation framework is a successor of Selenium RC, there are still a number of similarities as well as differences between the two. This article can help you develop a better understanding about the same and help you avoid any sort of confusion between the two.

  1. Browsers

Both these tools can be used on different browsers such as, Firefox, IE, Chrome, Safari, Opera and others.

  1. Recording and playback

Whether a user is using RC or WebDriver, it is possible for him/her to record as well as playback the execution of a test.

  1. Executing test script

While RC requires one to start server again before executing the test script, the same is not a mandate in case of WebDriver.

  1. Type of program

RC is a separate java program that allow a user execute HTML test suites. Whereas WebDriver is a programming interface which is available in multiple languages.

  1. Platform for interaction

RC server executes the test as JavaScript commands whereas WebDriver performs on Selenium commands and a browser.

  1. API

The API (Application Programming Interface) of RC is easy and small. But these contain a lot of redundancies and a lot of confusing commands. Various browsers interpret commands differently.
On the other hand, the API of WebDriver is large and a bit complex. These are also simple to comprehend and do not contain any sort of redundancy or confusing commands.

  1. Object-oriented

Selenium RC’s are not much object-oriented whereas Selenium WebDriver’s are completely object-oriented

  1. App testing

One cannot test any sort of iPhone or Android application on Selenium RC whereas the same can be done using WebDriver.

  1. XPath attachment

Selenium RC requires one to attach complete XPath whereas the same is not mandatory in case of WebDriver.

  1. Implementation of listeners

It is not possible to implant listeners in Selenium RC whereas one can do the same with a WebDriver.

  1. Execution speed

As compared to Selenium RC, WebDriver is faster in its execution as it is directly connected with the browser. The use of JavaScript program called Selenium Core slows down the Selenium RC’s speed.

  1. Syntax

While the syntax of RC is quite complex, the same is simple and easy to understand in case of WebDriver.
The basic purpose behind introducing Selenium WebDriver test automation framework in the market was to deal with the problem areas of Selenium RC as well as increase the scope of testing.

It is recommended to make use of Selenium WebDriver test automation framework for testing purposes however, the same depends on one’s choice as well the requirements.