Wednesday, 2 December 2020

Selenium Learnings - BASICS

So, Why the Name Selenium?

The Name Selenium came from a joke which Jason cracked once to his team. During Selenium's development, another automated testing framework was popular made by the company called Mercury Interactive (yes, the company who originally made QTP before it was acquired by HP). Since Selenium is a well-known antidote for Mercury poisoning, Jason suggested that name and his teammates took it. So that is how we got to call this framework up to the present.

What is Selenium Webdriver?

Selenium WebDriver is a collection of open source APIs which are used to automate the testing of a web application. ... It does not qualify for window-based applications. It also supports different programming languages such as C#, Java, Perl, PHP and Ruby for writing test scripts.

Who developed Selenium?

Primarily, Selenium was created by Jason Huggins in 2004. An engineer at ThoughtWorks, he was working on a web application that required frequent testing. Having realized that the repetitious Manual Testing of their application was becoming more and more inefficient, he created a JavaScript program that would automatically control the browser's actions. He named this program as the "JavaScriptTestRunner."

Seeing potential in this idea to help automate other web applications, he made JavaScriptRunner open-source which was later re-named as Selenium Core.

Benefits: 

Language Support. Multilingual support is one of the major benefits of Selenium WebDriver for automation testing. WebDriver supports all the programming languages that testers should know of such as like Python, PHP, Java, C#, Ruby, JavaScript etc

Challenges and limitations of Selenium WebDriver: 

  • Selenium cannot extend support to the Windows applications, it only works on the web based applications.
  • Selenium is not capable of performing mobile automation on its own.
  • Selenium does not have any inbuilt reporting feature.
  • Selenium has challenges handling frames and pop ups.
  • Selenium does not automate captcha.
  • Selenium does not automate barcodes.
  • Selenium depends on third party frameworks like TestNG, Cucumber for the reporting.
  • Selenium is open source, so in case of issues there is no prompt vendor assistance.
  • Selenium users need to be aware of some programming languages.
  • Selenium cannot perform testing for the images.
  • Selenium does not support automation testing of video and audio.
  • Selenium does not automate test cases on fingerprints.

Selenium tools: 

1. Selenium IDE

2. Selenium RC

3. Selenium Webdriver

4. Selenium Grid

At the moment, Selenium RC and WebDriver are merged into a single framework to form Selenium 2. Selenium 1, by the way, refers to Selenium RC.

Summary

The entire Selenium Tool Suite is comprised of four components:

  1. Selenium IDE, a Firefox add-on that you can only use in creating relatively simple test cases and test suites.
  2. Selenium Remote Control, also known as Selenium 1, which is the first Selenium tool that allowed users to use programming languages in creating complex tests.
  3. WebDriver, the newer breakthrough that allows your test scripts to communicate directly to the browser, thereby controlling it from the OS level.
  4. Selenium Grid is also a tool that is used with Selenium RC to execute parallel tests across different browsers and operating systems.

Selenium RC and WebDriver was merged to form Selenium 2.

Selenium is more advantageous than QTP in terms of costs and flexibility. It also allows you to run tests in parallel, unlike in QTP where you are only allowed to run tests sequentially.


Installation Key points:

what all you need in your system?

1. Java - JDK installation

2. Add Java in the system environments: Variable name as JAVA_HOME & Variable value as C:\******\Java\jdk-1.8.0_144

3. Update the JAVA_HOME in PATH variables. Click on Ok Button. Ex: %JAVA_HOME%\bin

4. Eclipse installation

5. Jar files to support Selenium, broswer etc according to the use. 


Where to find the jar files ?

Seleniumhq.org - https://www.selenium.dev/downloads/


what are all the jars required?

Selenium jar is must so download (selenium-server-standalone-3.141.5.jar) what ever the latest version at that time

I am planning to run my scripts in the chrome browser. so Chrome driver(chromedriver.exe). It support all browsers so download the jar files accordingly for the above link.


what next ?

1. Once all the above setup is done. Open eclipse and add the external jars.

2. How to add external Jars? To import jar file in your Eclipse IDE, follow the steps given below

  • Right click on your project.
  • Select Build Path.
  • Click on Configure Build Path.
  • Click on Libraries and select Add External JARs.
  • Select the jar file from the required folder.
  • Click and Apply and Ok.

3. Update JDK libraries into eclipse. Go to Eclipse->Window->Preferences->Java->Installed JRE’s

Initially it will point to JRE. Remove that one and add Jdk libraries from local folder.

Ex: C:\********\Java\jdk-1.8.0_144


Lets get the hands dirty in selenium coding

Open eclipse with a fresh project and a class and do the following steps,

1.Import WebDriver packages - import org.openqa.selenium.WebDriver

2. Import Browser drivers - import org.openqa.selenium.chrome.ChromeDriver

3. Set path of browser driver, using the “System.setProperty ” method, using which we can set up various driver specific properties, such as “webdriver.chrome.driver ” for chrome

Eg: System.setProperty("webdriver.chrome.driver", "Path where you have saved the chromedriver.exe"); //same path but with double "\\"

4. Object Instantiation of WebDriver

Eg: WebDriver driver=new ChromeDriver();


How to navigate to a web page using Selenium WebDriver?

There are two methods in Selenium WebDriver using which you can navigate to a particular web page.


driver.get(“URL”) – Navigates to the URL passed as an argument and waits till the page loads

driver.get("www.google.com");


how to Maximize browser window using Selenium Webdriver?

driver.manage().window().maximize();

manage() method returns an instance of the Options interface, now this Options interface has a window method that returns Window type. We then use the maximize method of the Window interface to maximize the browser window.


How to Retrieve the title of the page:

getTitle()

It fetches the title of the currently opened web page and returns the same as a String. In the code below, the driver variable calls the getTitle() method and stores the values in a string variable ‘title.’ We are then printing this string variable on the console window  using the Java print statement:

String title = driver.getTitle();

System.out.println("The page title is : " +title);


How to close the browser using Selenium WebDriver?

The last step that marks the closing of your test script is the closing of the browser. You can close the browser using any of the following methods provided by Selenium WebDriver:

close() – It closes the current browser window.

quit() – It calls the dispose() method of the WebDriver that closes all the browser windows opened by the WebDriver and terminates the WebDriver session. It’s always recommendable to use the quit() method as it releases the driver.

driver.close();

driver.quit();


The commands provided by Selenium WebDriver can be broadly classified in following categories:


  • Browser Commands
  • Navigation Commands
  • WebElement Commands


1. Selenium Webdriver Browser Commands

Now the next question is, How to access the methods of WebDriver? To check what all we have in WebDriver, create a driver object from WebDriver and press dot key. This will list down all the methods of WebDriver.

Method: A Java method is a collection of statements that are grouped together to perform an operation.

Eg: get(String arg0):void

Method Name: To access any method of any class, we need to create an object of a class and then all the public methods will appear for the object.

Parameter: It is an argument that is passed to a method as a parameter to perform some operation. Every argument must be passed with the same data type. For e.g. get(String arg0) : void. This is asking for a String type argument.

Return Type: Method can return a value or returning nothing (void). If the void is mentioned after the method, it means the method is returning no value. And if it is returning any value, then it must display the type of the value for e.g. getTitle() : String.


Get-Command – How to Open a WebPage in Selenium?

get(String arg0): void – This method Load a new web page in the current browser window. Accepts String as a parameter and returns nothing.

Command – driver.get(appUrl);


Get Title Command – How to get the Title of the Webpage in Selenium? 

getTitle(): String – This method fetches the Title of the current page. Accepts nothing as a parameter and returns a String value.

Command – driver.getTitle();


Get Current URL Command – How to read the URL of the Webpage in Selenium

getCurrentUrl(): String – This method fetches the string representing the Current URL which is opened in the browser. Accepts nothing as a parameter and returns a String value.

Command – driver.getCurrentUrl();


Get Page Source Command – How to read the page source of the WebPage in Selenium?

getPageSource(): String – This method returns the Source Code of the page. Accepts nothing as a parameter and returns a String value.

Command – driver.getPageSource();


Close Command – How to close the Browser in Selenium?

close(): void – This method Close only the current window the WebDriver is currently controlling. Accepts nothing as a parameter and returns nothing.

Command – driver.close();


Quit Command – How to close all the Browser’s Window in Selenium?

quit(): void – This method Closes all windows opened by the WebDriver. Accepts nothing as a parameter and returns nothing.

Command – driver.quit();


Activity : To praticise the above commands:

Launch a new Chrome browser.

Open any website

Get Page Title name and Title length

Print Page Title and Title length on the Eclipse Console.

Get Page URL and verify if it is a correct page opened

Get Page Source (HTML Source code) and Page Source length

Print Page Length on Eclipse Console.

Close the Browser.


2. Selenium Webdriver – Browser Navigation Command


To access the navigation’s method, just type driver.navigate(). The IntelliSense feature of the eclipse will automatically display all the public methods of Navigate Interface


Navigate To Command – How to Navigate to URL or How to open a webpage in Selenium Browser?

to(String arg0) : void – This method Loads a new web page in the current browser window. It accepts a String parameter and returns nothing.

Command – driver.navigate().to(appUrl);


Forward Command – How to browser Forward in Selenium Browser?

forward() : void – This method does the same operation as clicking on the Forward Button of any browser. It neither accepts nor returns anything.

Command – driver.navigate().forward();


Back Command – How to browse backward in Selenium Browser?

back() : void – This method does the same operation as clicking on the Back Button of any browser. It neither accepts nor returns anything.

Command – driver.navigate().back();


Refresh Command – How to Refresh Selenium Browser?

refresh() : void – This method Refresh the current page. It neither accepts nor returns anything.

Command – driver.navigate().refresh();


3. Selenium Webdriver – WebElement Command


What is WebElement?

WebElement represents an HTML element. HTML documents are made up by HTML elements. HTML elements are written with a start tag, with an end tag, with the content in between: <tagname> content </tagname>

The HTML element is everything from the start tag to the end tag: <p> My first HTML paragraph. </p>

HTML elements can be nested (elements can contain elements). All HTML documents consist of nested HTML elements.


How to locate a web element on a web page using Selenium WebDriver?

The next step towards writing the automation scripts is locating the web elements we want to interact with. Selenium WebDriver provides various locator strategies using which it can locate various web elements on a page. The “By” provides all these locators. Class of Selenium WebDriver. 


For our example scenario, we have used the XPath locator strategy for locating the userName, password, and login button elements, as shown below:

WebElement uName = driver.findElement(By.xpath("//*[@id='userName']"));

WebElement pswd = driver.findElement(By.xpath("//*[@id='password']"));

WebElement loginBtn = driver.findElement(By.xpath("//*[@id='login']"))

or by using ID locator,

WebElement element = driver.findElement(By.id(“UserName“));


And now if you type element dot, Eclipse’s intellisence will populate the complete list of actions.


Selenium defines two methods for identifying web elements:

findElement: A command used to uniquely identify a web element within the web page.

findElements: A command used to identify a list of web elements within the web page.


Difference between findElement and findElements

findElement findElements

1.Returns the first matching web element if multiple web elements are discovered by the locator

1.Returns a list of multiple matching web elements

2.Throws NoSuchElementException if the element is not found

2.Returns an empty list if no matching element is found

3.Detects a unique web element

3.Returns a collection of matching elements


As you can see that the different Web Elements store in variables that would perform actions on these elements. With this, you will also notice two more import statements added to your code:

import org.openqa.selenium.By; – It references the By class through which we call the locator type.

import org.openqa.selenium.WebElement; – It references the WebElement class that helps instantiate a new web element.


What is the difference between WebDriver and WebElement?

The WebDriver class focuses on driving the browser in a broad sense. It loads pages, it switches to different windows/frames, gets the page title etc. Broad actions that aren't specific to an element on the page. WebElement concentrates on interacting with a specific element that you've located.


List of WebElement Commands/Actions


Clear Command

WebElement element = driver.findElement(By.id("UserName"));  

element.clear(); 


Sendkeys Command

driver.findElement(By.id("UserName")).sendKeys("JavaTpoint"); 


Click Command

driver.findElement(By.linkText("javaTpoint")).click();  


IsDisplayed Command

boolean status = driver.findElement(By.id("UserName")).isDisplayed(); 


IsEnabled Command

boolean status = driver.findElement(By.id("UserName")).isEnabled(); 


IsSelected Command

boolean staus = driver.findElement(By.id("Sex-Male")).isSelected();  


Submit Command

driver.findElement(By.id("SubmitButton")).submit();  


GetText Command

WebElement element = driver.findElement(By.xpath("anyLink"));  

String linkText = element.getText();


GetTagName Command

WebElement element = driver.findElement(By.id("SubmitButton"));  

String tagName = element.getTagName(); 


getCssValue Command

element.getCssValue();  


getAttribute Command

WebElement element = driver.findElement(By.id("SubmitButton"));  

String attValue = element.getAttribute("id"); //This will return "SubmitButton"  


getSize Command

WebElement element = driver.findElement(By.id("SubmitButton"));  

Dimension dimensions = element.getSize();  

System.out.println("Height :" + dimensions.height + "Width : "+ dimensions.width);  


getLocation Command

WebElement element = driver.findElement(By.id("SubmitButton"));  

Point point = element.getLocation();  

System.out.println("X cordinate : " + point.x + "Y cordinate: " + point.y);  


How to perform actions on web elements using Selenium WebDriver?

After we have located the web elements and stored them as WebElement instances, we will be performing actions on them like entering text for the user name and password and clicking on the login button. Selenium WebDriver provides multiple methods to perform actions on various web elements. A few of those methods exposed by the WebElement  interface are:


sendKeys() – used to enter text in the web element

submit() – used to submit a form

click() – used to perform click on the web element

clear() – used to clear entered text


Find elements using Selenium WebDriver


Why do we need to find an element in Selenium?

We know that we use Selenium mostly for UI testing of a web-based application. Since we need to perform automatic feature interaction with the web page, we need to locate web elements so that we can trigger some JavaScript events on web elements like click, select, enter, etc. or add/ update values in the text fields. To perform these activities it is important to first locate the element on the web page and then perform all these actions.


What is By class in Selenium?

In this section, we will understand how to use Selenium WebDriver’s findElement() and findElements() with different strategies using the By class. The ‘By ‘ class accepts various locator strategies explained above to find an element or elements on a web page. Let us discuss all the By class locator strategies.


What are all the various methods to Find elements using Selenium WebDriver?


Locator Description

class name Locates elements whose class name contains the search value (compound class names are not permitted)

css selector Locates elements matching a CSS selector

id Locates elements whose ID attribute matches the search value

name Locates elements whose NAME attribute matches the search value

link text Locates anchor elements whose visible text matches the search value

partial link text Locates anchor elements whose visible text contains the search value. If multiple elements are matching, only the first one will be selected.

tag name Locates elements whose tag name matches the search value

xpath Locates elements matching an XPath expression


Eg: 

driver.findElement(By.LocatorStrategy("LocatorValue"));


1. How to find an element using the attribute “id” in Selenium?

Using “id ” to find an element is by far the most common strategy used to find an element. Suppose if the webpage uses dynamically generated ids, then this strategy returns the first web element that matches the id.

This strategy is preferred as most web pages are designed by associating ids with the elements. This is because using IDs is the easiest and quickest way to locate elements because of its simplicity while coding a web page. The value of the id attribute is a String type parameter.

The general syntax of findElement() command using By id strategy is :


driver.findElement(By.id("element ID"));

driver.findElement(By.id("submit"));


2. How to find an element using the attribute “name” in Selenium?

This strategy is the same as id except that the locator locates an element using the “name” instead of “id “.

The value of the NAME attribute accepted is of type String. The general syntax of the findElement() method with By Name strategy is as below.

driver.findElement (By.name("gender"));


3. How to find an element using the attribute “class name” in Selenium?

Here the value of the “class” attribute is passed as the locator. This strategy is mostly used to find multiple elements that use similar CSS classes.

The locator strategy ‘By Class Name‘ finds the elements on the web page based on the CLASS attribute value. The strategy accepts a parameter of type String. The general syntax with the Class name strategy is given by:

driver.findElement(By.className("button"));

If same class name share with more than one element?

List<WebElement> webList = driver.findElements(By.className(<Element_CLASSNAME>)) ;


4. How to find an element using the attribute “HTML tag name” in Selenium?

The Tag Name strategy uses an HTML tag name to locate the element. We use this approach rarely and we use it only when we are not able to find elements using any other strategies.

The value of the TAG attribute is a String type parameter. The syntax of the findElement() method using this strategy is as below.

driver.findElement(By.tagName("input"));


5. How to find an element using the “CSS Selector” in Selenium?

We can also use the CSS Selector strategy as an argument to By object when finding the element. Since CSS Selector has native browser support, sometimes the CSS Selector strategy is faster than the XPath strategy.

driver.findElement(By.cssSelector("input[id = 'firstName']"))


6. How to find an element using the “XPath” in Selenium?

This strategy is the most popular one for finding elements. Using this strategy we navigate through the structure of the HTML or XML documents.

This strategy accepts a String type parameter, XPath Expression. The general syntax of using this strategy is as given below:

WebElement buttonLogin = driver.findElement(By.xpath("//button[@id = 'submit']"));


driver.findElement(By.xpath("//button[@id = 'submit']"));


Types of X-path

There are two types of XPath:

1) Absolute XPath

2) Relative XPath


Absolute XPath:

It is the direct way to find the element, but the disadvantage of the absolute XPath is that if there are any changes made in the path of the element then that XPath gets failed.

The key characteristic of XPath is that it begins with the single forward slash(/) ,which means you can select the element from the root node.

Below is the example of an absolute xpath expression of the element shown in the below screen.

Syntax for XPath:

/html/body/div[2]/div[1]/div/h4[1]/b/html[1]/body[1]/div[2]/div[1]/div[1]/h4[1]/b[1]


Relative Xpath:

Relative Xpath starts from the middle of HTML DOM structure. It starts with double forward slash (//). It can search elements anywhere on the webpage, means no need to write a long xpath and you can start from the middle of HTML DOM structure. Relative Xpath is always preferred as it is not a complete path from the root element.

Below is the example of a relative XPath expression of the same element shown in the below screen. This is the common format used to find element through a relative XPath.


Relative XPath: //div[@class='featured-box cloumnsize1']//h4[1]//b[1]

XPath contains the path of the element situated at the web page. Standard syntax for creating XPath is.

Xpath=//tagname[@attribute='value']

// : Select current node.

Tagname: Tagname of the particular node.

@: Select attribute.

Attribute: Attribute name of the node.

Value: Value of the attribute.


Using XPath Handling complex & Dynamic elements in Selenium

1) Basic XPath:

XPath expression select nodes or list of nodes on the basis of attributes like ID , Name, Classname, etc. from the XML document as illustrated below.

Xpath=//input[@name='uid']

Xpath=//input[@type='text']

Xpath= //label[@id='message23']

Xpath= //input[@value='RESET']

Xpath=//*[@class='barone']

Xpath=//a[@href='http://demo.com/']

Xpath= //img[@src='//cdn.com/images/home/java.png']


2) Contains():

Contains() is a method used in XPath expression. It is used when the value of any attribute changes dynamically, for example, login information.

The contain feature has an ability to find the element with partial text as shown in below example.

In this example, we tried to identify the element by just using partial text value of the attribute. In the below XPath expression partial value 'sub' is used in place of submit button. It can be observed that the element is found successfully.

Xpath=//*[contains(@type,'sub')]  

Xpath=//*[contains(@name,'btn')]


3) Using OR & AND:

In OR expression, two conditions are used, whether 1st condition OR 2nd condition should be true. It is also applicable if any one condition is true or maybe both. Means any one condition should be true to find the element.


In the below XPath expression, it identifies the elements whose single or both conditions are true.

Xpath=//*[@type='submit' or @name='btnReset'

In AND expression, two conditions are used, both conditions should be true to find the element. It fails to find element if any one condition is false.

Xpath=//input[@type='submit' and @name='btnLogin']


4) Xpath Starts-with

XPath starts-with() is a function used for finding the web element whose attribute value gets changed on refresh or by other dynamic operations on the webpage. In this method, the starting text of the attribute is matched to find the element whose attribute value changes dynamically. You can also find elements whose attribute value is static (not changes).

For example -: Suppose the ID of particular element changes dynamically like:

Id=" message12"

Id=" message345"

Id=" message8769"

and so on.. but the initial text is same. In this case, we use Start-with expression.


In the below expression, there are two elements with an id starting "message"(i.e., 'User-ID must not be blank' & 'Password must not be blank'). In below example, XPath finds those element whose 'ID' starting with 'message'.

Xpath=//label[starts-with(@id,'message')]


5) XPath Text() Function

The XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes. The elements to be located should be in string form.

In this expression, with text function, we find the element with exact text match as shown below. In our case, we find the element with text "UserID".

Xpath=//td[text()='UserID']


6) XPath axes methods:

These XPath axes methods are used to find the complex or dynamic elements. Below we will see some of these methods.


a) Following:

Selects all elements in the document of the current node( ) [ UserID input box is the current node] as shown in the below screen.

Xpath=//*[@type='text']//following::input

There are 3 "input" nodes matching by using "following" axis- password, login and reset button. If you want to focus on any particular element then you can use the below XPath method:

Xpath=//*[@type='text']//following::input[1]


b) Ancestor:

The ancestor axis selects all ancestors element (grandparent, parent, etc.) of the current node as shown in the below screen.

In the below expression, we are finding ancestors element of the current node("ENTERPRISE TESTING" node).

Xpath=//*[text()='Enterprise Testing']//ancestor::div

Xpath=//*[text()='Enterprise Testing']//ancestor::div[1]


c) Child:

Selects all children elements of the current node (Java) as shown in the below screen.

Xpath=//*[@id='java_technologies']//child::li

There are 71 "li" nodes matching by using "child" axis. If you want to focus on any particular element then you can use the below xpath:

Xpath=//*[@id='java_technologies']/child::li[1]


d) Preceding:

Select all nodes that come before the current node as shown in the below screen.

In the below expression, it identifies all the input elements before "LOGIN" button that is Userid and password input element.

Xpath=//*[@type='submit']//preceding::input

There are 2 "input" nodes matching by using "preceding" axis. If you want to focus on any particular element then you can use the below XPath:

Xpath=//*[@type='submit']//preceding::input[1]


e) Following-sibling:

Select the following siblings of the context node. Siblings are at the same level of the current node as shown in the below screen. It will find the element after the current node.

xpath=//*[@type='submit']//following-sibling::input

 

f) Parent:

Selects the parent of the current node as shown in the below screen.

There are 65 "div" nodes matching by using "parent" axis. If you want to focus on any particular element then you can use the below XPath:

Xpath=//*[@id='rt-feature']//parent::div[1]


g) Self:

Selects the current node or 'self' means it indicates the node itself as shown in the below screen.

One node matching by using "self " axis. It always finds only one node as it represents self-element.

Xpath =//*[@type='password']//self::input


h) Descendant:

Selects the descendants of the current node as shown in the below screen.

In the below expression, it identifies all the element descendants to current element ( 'Main body surround' frame element) which means down under the node (child node , grandchild node, etc.).

Xpath=//*[@id='rt-feature']//descendant::a

Xpath=//*[@id='rt-feature']//descendant::a[1]


Summary:

XPath is required to find an element on the web page as to do an operation on that particular element.

There are two types of XPath:

  1. Absolute XPath
  2. Relative XPath

XPath Axes are the methods used to find dynamic elements, which otherwise not possible to find by normal XPath method

XPath expression select nodes or list of nodes on the basis of attributes like ID , Name, Classname, etc. from the XML document .


Locating Web Elements In Google Chrome

Let us begin with understanding the locating strategies in Google Chrome.

Like Firebug in Firefox, Google Chrome has its own developer tool that can be used to identify and locate web elements on the web page. Unlike firebug, a user is not required to download or install any separate plugin; the developer tool comes readily bundled with Google Chrome.


Follow the below steps to locate web elements using Chrome’s Developer tool:

Step #1: The primary step is to launch the Google Chrome’s Developer tool. Press F12 to launch the tool. The user would be able to see something like the below screen.

Take a note that “Element” tab is highlighted. Thus, 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.

You can also launch developer tool by right-clicking anywhere within the web page and by selecting “Inspect element” which is very similar to that of firebug’s inspection.

Step #2: The next step is to locate the desired object within the web page. One way to do the same is to right click on the desired web element and inspect. The HTML property belonging to that web element would be highlighted in the developer tool. Another way is to hover through the HTML properties and the matching web element would be highlighted. Thus, in this way user can locate ids, class, links etc


Creating an Xpath in Developer Tool

We have already discussed Xpaths in the last tutorial. We also discussed its creation strategy. Here we would base our discussion to check the validity of the created XPath in Chrome’s Developer tool.


Step #1: For creating XPath in Developer tool, open the console tab.

Step #2: Type the created Xpath and enclose it in $x(“//input[@id=’Email’]”)

Step #3: Press the enter key to see all the matching HTML elements with the specified Xpath. In our case, there is only one matching HTML element. Hover on that HTML element and the corresponding web element would be highlighted on the web page.

To Summarize:

  • We need to find or locate web elements within the webpage so that we can perform actions on these elements.
  • Additionally, we have two methods find Element and find Elements methods in Selenium WebDriver using which we can locate elements.
  • Also, the method findElement() in Selenium returns a unique web element from the webpage.
  • The method findElements() in Selenium returns a list of web elements
  • Lastly, to locate or find the elements each method uses a locator strategy which is provided via an argument to the “By” object. These strategies are by Id, by Name, by Class Name, by XPath, by link, etc.

CheckBox, Radio button and Dropdown 

How to handle CheckBox in Selenium WebDriver?

The checkbox is a GUI element that allows the user to make certain choices for the given options. Users may get a list of choices, and the checkbox records the choices made by the user. The checkbox allows users to select either single or multiple choices out of the given list.

Apart from “Checked ” and “UnChecked“, sometimes applications provide a tri-state/intermediate, which we generally use when a neutral answer needs to provide for an option or which is an auto-selection for a parent when the child checkbox is selected

If we look at the HTML structure of the above element, we will find that it starts with the <input type=“checkbox”>  node. We have highlighted the HTML structure of the checkboxes 

<input type="checkbox" id="hobbies-checkbox-1" class="custom-control-input" value="1">

As we can see, all the checkboxes are being created using the HTML tag <input> and have an attribute named “type”, which has a value “checkbox“, which signifies that the type of the input element is a checkbox.

Now, let’s see how we can locate and perform specific actions on the CheckBoxes using Selenium WebDriver?

driver.findElement(By.id("hobbies-checkbox-1")).click();

<label title="" for="hobbies-checkbox-1" class="custom-control-label">Sports</label>

driver.findElement(By.xpath("//label[text()='Sports']")).click();
 
driver.findElement(By.xpath("//label[text()='Reading']")).click();

How to perform validations on a CheckBox using Selenium WebDriver?
Selenium WebDriver provides certain methods that we can use for a pre and post validation of the states of a CheckBox. Few of these methods are:

isSelected(): Checks whether a checkbox is selected or not.
eg:
WebElement checkBoxElement = driver.findElement(By.cssSelector("label[for='hobbies-checkbox-1']"));
boolean check = checkBoxElement.isSelected();
 
//performing click operation if element is not checked
if(check == false) {
 checkBoxElement.click();
 
isDisplayed(): Checks whether a checkbox displays on the web page or not.
eg:
WebElement checkBoxElement = driver.findElement(By.cssSelector("label[for='hobbies-checkbox-1']"));
boolean isDisplayed = checkBoxElement.isDisplayed();
 
// performing click operation if element is displayed
if (isDisplayed == true) {
 checkBoxElement.click();

isEnabled(): Checks whether a checkbox is enabled or not
eg:
WebElement checkBoxElement = driver.findElement(By.cssSelector("label[for='hobbies-checkbox-1']"));
boolean isEnabled = chckBxEnable.isEnabled();
 
// performing click operation if element is enabled
if (isEnabled == true) {
 checkBoxElement.click(); 
 
Keypoints
  1. CheckBoxes are denoted by <input type=”checkbox“> HTML tag
  2. We can identify the Checkbox elements by locator strategies such as id, XPath, CSS selector, or any other selenium locator that can uniquely identify the checkbox
  3. We can select a checkbox either by using the click() method on the input node or on the label node that represents the checkbox.
  4. Selenium also offers validation methods like isSelected, isEnabled, and isDisplayed. We can use these methods to make sure checkboxes are in the correct status before performing any operation.


How to handle Radio Button in Selenium WebDriver?
A radio button in HTML is defined using <input> tag and an attribute “type”, which will have the value as “radio”. So any locator strategy that uses DOM for identifying and locating the elements will use the <input> tag for recognizing the radio buttons.

If we look at the HTML structure of the above element, we will find that it starts with the <input> tag,

<input name="gender" required="" type="radio" id="gender-radio-1" class="custom-control-input" value="Male">
<label title="" for="gender-radio-1" class="custom-control-label">Male</label>

As we can see, all the radio buttons are being created using the HTML tag <input> and have an attribute named “type“, which has a value “radio”, which signifies that the type of the input element is a radio button

driver.findElement(By.id("gender-radio-1")).click();
driver.findElement(By.name("gender")).click();
driver.findElement(By.xpath("//div/input[@id='gender-radio-1']")).click();


How to perform validations on Radio Buttons using Selenium WebDriver?

isSelected(): Checks whether a radio button is selected or not.
WebElement radioElement = driver.findElement(By.id("impressiveRadio"));
boolean selectState = radioElement.isSelected();
 
//performing click operation only if element is not selected
if(selectState == false) {
 radioElement.click();
}
isDisplayed(): Checks whether a radion button is displayed on the web page or not.
WebElement radioElement = driver.findElement(By.id("impressiveRadio"));
boolean selectState = radioElement.isDisplayed();
 
//performing click operation only if element is not selected
if(selectState == false) {
 radioElement.click();
}
isEnabled(): Checks whether a radion button is enabled or not
WebElement radioElement = driver.findElement(By.id("noRadio"));
boolean selectState = radioElement.isEnabled();
 
//performing click operation only if element is not selected
if(selectState == false) {
 radioElement.click();
}


Dropdown in Selenium

In HTML, the dropdowns are generally implemented either using the <select> tag or the <input> tag. To perform certain operations on the dropdowns, which are declared using the <select> HTML tag, Selenium WebDrivers provides a class called “Select ” class.

the “Select ” class is provided by the “org.openqa.selenium.support.ui ” package of Selenium WebDriver. You can create an object of the Select class, by-passing the object of the “WebElement” class, which shows the object returned by the corresponding locator of the WebElement.

Select select = new Select(WebElement webelement);

How to select a value from a dropdown in Selenium?
selectByIndex
selectByValue
selectByVisibleText

The index starts at 0.

Select se = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']")));
 
// Select the option by index
se.selectByIndex(3);
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Create object of the Select class
Select se = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']")));
// Select the option with value "6"
se.selectByValue("6");
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Select se = new Select(driver.findElement(By.xpath("//*[@id='oldSelectMenu']")));
 
// Select the option using the visible text
se.selectByVisibleText("White");

Multiple Select 

Select multi = new Select(driver.findElement(By.id("cars")));
//isMultiple() ” method, which determines whether the web element in say supports multiple selections
   
 if (multi.isMultiple());
    {
    multi.selectByIndex(1);
    multi.selectByIndex(2);
   
     
    //Or selecting by values
    multi.selectByValue("volvo");
    multi.selectByValue("audi");
     
    //Or selecting by visible text
    multi.selectByVisibleText("Volvo");
    multi.selectByVisibleText("Opel");
    }
 

Tables

What is Table in HTML?

Table is a kind of HTML data which is displayed with the help of <table> tag in conjunction with the <tr> and <td> tags. Although there are other tags for creating tables, these are the basics for creating a table in HTML. Here tag <tr> defines the row and tag <td> defines the column of the table.

 

Name

Emp id

Project

Ane

123

CSB

Pingu

456

BOI

Panda

678

CISCO

 

<table class=”dataTable”>

<tbody>

 <tr>

   <th>Name</th>

   <th>Emp id</th>

   <th>Project</th>

 </tr>

 <tr>

   <td>Ane</td>

   <td>123</td>

   <td>CSB</td>

 </tr>

 <tr>

   <td>Pingu</td>

   <td>456</td>

   <td>BOI</td>

 </tr>

<tr>

   <td>Panda</td>

   <td>678</td>

   <td>CISCO</td>

 </tr>

 </tbody>

</table>

 

 // To get the size of the table

            List<WebElement> col = driver.findElements(By.xpath("//table[@class='dataTable']//tr[1]//th"));

            System.out.println(col.size());

           

            List<WebElement> row = driver.findElements(By.xpath("//table[@class='dataTable']//tr"));

            System.out.println(row.size());

 

To fetch the all the data from the table

List<WebElement> allRows = driver.findElements(By.xpath("//table[@class='dataTable']//tr"));

           

            // And iterate over them and get all the cells

            for (WebElement rows : allRows) {

                List<WebElement> cells = rows.findElements(By.tagName("td"));

 

                // Print the contents of each cell

                for (WebElement cell : cells) {        

 

                System.out.println(cell.getText());

   The above code fetches all the data inside a table,

1. Collecting all the rows in a list called "allRows"

2. Using for each loop transfer the rows to "row" (one by one of all the rows)

3. in each row find the elements contains the tag "td" (td contains the data)

4. collecting all the td values in a list called "cells" 

5. using for each loop transfer the td values to "cell"

6. Print all the values using gettext()      

 

No comments:

Post a Comment