Table of Contents
What we have learned so far?
Part 1 – What is Selenium WebDriver? How to setup Selenium?
Locators in Selenium WebDriver
Selenium WebDriver have different ways to select a HTML element. We can use these different ways as locating strategy.
What is HTML element?
An HTML element usually consists of a start tag and an end tag, with the content inserted in between:
<tagname>Content goes here…</tagname>
The HTML element is everything from the start tag to the end tag:
If you don’t know about the HTML elements then you can go through below links –
HTML Elements – https://www.w3schools.com/html/html_elements.asp
HTML Attributes – https://www.w3schools.com/html/html_attributes.asp
HTML Input Types – https://www.w3schools.com/html/html_form_input_types.asp
HTML Form Attributes – https://www.w3schools.com/html/html_form_attributes.asp
HTML Forms – https://www.w3schools.com/html/html_forms.asp
Locators in Selenium WebDriver
There are total 7 ways to locate or find the
Finding the html element information using Chrome / Firefox
Launch the web browser (Chrome / Firefox) and navigate to https://onlyfullstack.blogspot.com/2020/03/best-demo-website-to-practice-selenium.html
Open firebug (either by pressing F12 or via tools). or write click on any html element on the page and click on Inspect.
Step 1: Click on the inspect icon to identify the web element.
Step 2: Select the element for which you want to view the html code.
Step 3: It will show the corresponding html for that element.
How to find the elements in Selenium?
We can find the elements in selenium with the help of findElement method. This method will return the WebElement object on which we can perform various operations as below :
- Click on button
- Enter values inside textfield
- Get the text of the HTML element and so on
webDriver.findElement(element_to_be_search);
We can select an element from its id attribute. id is unique throughout the page. Lets see how to find the html element and its attributes.
How to use Developer Tool to view HTML element
Open https://onlyfullstack.blogspot.com/2020/03/best-demo-website-to-practice-selenium.html
2. Click on Inspect
3. This will open the developer mode and highlight the name input box.
4. Copy the value of id.
Now we have got the id so we can use this value to locate the name text field for us. id is unique in the page so its always recommended to use id over other locators strategies.
Lets write the code for this
package com.onlyfullstack.selenium; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; public class SeleniumLocators { public static void main(String[] args) throws InterruptedException { System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, "Documents/chrome-web-driver/chromedriver"); WebDriver webDriver = new ChromeDriver(); webDriver.get("https://onlyfullstack.blogspot.com/2020/03/best-demo-website-to-practice-selenium.html"); webDriver.manage().window().maximize(); JavascriptExecutor js = (JavascriptExecutor) webDriver; js.executeScript("window.scrollBy(0,2200)"); locateById(webDriver); Thread.sleep(3000); webDriver.close(); } private static void locateById(WebDriver webDriver) { WebElement nameTextField = webDriver.findElement(By.id("name-text-field-id")); nameTextField.sendKeys("Only FullStack "); } }
Lets understand the code we have written –
Below piece of code is responsible to scroll down by 2200 px so that we can view our form.
webDriver.manage().window().maximize(); JavascriptExecutor js = (JavascriptExecutor) webDriver; js.executeScript("window.scrollBy(0,2200)");
We are using the static method id() of class By and provided our id which we have copied form the chrome Inspect element. findElement(locator) will return the object of WebElement which we can use to perform different operations. Here we will type Only Fullstack into our name text box. WebElement has an instance method called sendKeys(values_to_type_in_text_box) which accepts string as a parameter.
private static void locateById(WebDriver webDriver) { WebElement nameTextField = webDriver.findElement(By.id("name-text-field-id")); nameTextField.sendKeys("Only FullStack"); }
2. Class Name as Locator in Selenium WebDriver
We can also select an element with class name. Lets select an email id text box with clsss name.
Here we are finding the email id text box and sending the key(giving the value in text box)s as onlyfullstack@gmail.com. Here we have used By.className method and rest of the code is same.
private static void locateByClass(WebDriver webDriver) { WebElement nameTextField = webDriver.findElement(By.className("email-text-field-class")); nameTextField.sendKeys("onlyfullstack@gmail.com "); }
3. Name as Locator in Selenium WebDriver
We can also select an element with class name. Lets select a zip code text box with html name attribute.
private static void locateByName(WebDriver webDriver) { WebElement nameTextField = webDriver.findElement(By.name("Zip")); nameTextField.sendKeys("411033 "); }
What is XPath?
XPath is defined as XML path. It is a syntax or language for finding any element on the web page using XML path expression. XPath is used to find the location of any element on a webpage using HTML DOM structure. HTML is the nested language and we can find any element through the XPath. XPath is the complete navigation to the html element.
You can find the XPath of any element with the help of developer tool. Lets find the XPath of the About Yourself text area on below link
https://onlyfullstack.blogspot.com/2020/03/best-demo-website-to-practice-selenium.html
Right click on that texture and click on inspect. The developer tool will come up and it will show the XPath of that text area at the bottom.
Types of XPath
What is the difference between Absolute and Relative XPath?
1) Absolute XPath
It uses Complete path from the Root Element to the desire element.
You can copy the Absolute Path of any element as below :
Inspect that element in FireFox or Chrome and Right Click on that element -> Copy -> Copy full XPath
Absolute Path of our About yourself textarea is
/html/body/div[1]/div/div/main/div/div[8]/div/div/div[1]/div[2]/div[2]/div/div/div/div/div/form/table/tbody/tr[8]/td[2]/textarea
2) Relative XPath
Relative XPath finds the closed id to the dom element and generates xpath starting from that element.
Always Relative Xpaths are preferred as they are not the complete paths from the Root element. (//html//body) ..Beacuse in future any of the webelement when added/Removed then Absolute Xpath changes. So Always use Relative Xpaths in your Automation.
Inspect that element in FireFox or Chrome and Right Click on that element -> Copy -> Copy XPath
Absolute Path of our About yourself textarea is
//*[@id=”post-body-39246966950473039″]/div/form/table/tbody/tr[8]/td[2]/textarea
Here we are finding the About yourself texture and sending the keys(giving the value in text box) as “I like programming”. Here we have used By.xpath method and rest of the code is same.
private static void locateByAbsoluteXPath(WebDriver webDriver) { WebElement nameTextField = webDriver.findElement(By.xpath("/html/body/div[1]/div/div/main/div/div[8]/div/div/div[1]/div[2]/div[2]/div/div/div/div/div/form/table/tbody/tr[8]/td[2]/textarea")); nameTextField.sendKeys("I like programming."); } private static void locateByRelativeXPath(WebDriver webDriver) { WebElement nameTextField = webDriver.findElement(By.xpath("//*[@id="post-body-39246966950473039"]/div/form/table/tbody/tr[8]/td[2]/textarea")); nameTextField.sendKeys("I like programming. "); }
5. Tag Name as Locator in Selenium WebDriver
We can also select an element with tag name. Lets select a Terms and Conditions link and text box with html name attribute.
Now in our page we have lots of anchor tags <a> so we will use the findElements(locator) method which will return the list of all the WebElements of anchor tags available in our page. Here we are iterating through the List<WebElements> and comparing the anchor text with “Terms and Conditions”.
private static void locateByTagName(WebDriver webDriver) throws InterruptedException { List<WebElement> links = webDriver.findElements(By.tagName("a")); for(WebElement webElement : links) { if("Terms and Conditions".equals(webElement.getText())) { webElement.click(); Thread.sleep(1000); webDriver.switchTo().alert().accept(); } } }
6. CSS Selectors in Selenium WebDriver
CSS selector can also locate web elements having no ID, class or Name.
So now gearing ahead, let us discuss the primitive types of CSS Selectors:
6.1. CSS Selector by ID
Syntax
html_element#id_name
HTML tag – It is the tag which is used to denote the web element which we want to access.
# – The hash sign is used to symbolize ID attribute. It is mandatory to use hash sign if ID attribute is being used to create CSS Selector.
Value of ID attribute – It is the value of an ID attribute which is being accessed.
The value of ID is always preceded by a hash sign.
So here we will use input#name-text-field-id
private static void locateByCssSelectorId(WebDriver webDriver) { WebElement nameTextField = webDriver.findElement(By.cssSelector("input#name-text-field-id")); nameTextField.sendKeys("Only FullStack with css selector id"); }
6.2. CSS Selector by Class
Syntax
html_element.class_name
HTML tag – It is the tag which is used to denote the web element which we want to access.
.(dot) – The dot sign is used to symbolize class attribute. It is mandatory to use dot sign if class attribute is being used to create CSS Selector.
Value of ID attribute – It is the value of an ID attribute which is being accessed.
The value of ID is always preceded by a hash sign.
So here we will use input.email-text-field-class
private static void locateByCssSelectorClass(WebDriver webDriver) { WebElement nameTextField = webDriver.findElement(By.cssSelector("input.email-text-field-class")); nameTextField.sendKeys("onlyfullstack@gmail.com "); }
6.3. CSS Selector by Attribute
Syntax
html_element[attribute=value_of_attribute]
Attribute – It is the attribute we want to use to create CSS Selector. It can value, type, name etc. It is recommended to choose an attribute whose value uniquely identifies the web element.
Value of attribute – It is the value of an attribute which is being accessed.
private static void locateByCssSelectorClass(WebDriver webDriver) { WebElement nameTextField = webDriver.findElement(By.cssSelector("input.email-text-field-class")); nameTextField.sendKeys("onlyfullstack@gmail.com"); }
6.4. CSS Selector by Sub String
CSS in Selenium allows matching a partial string and thus deriving a very interesting feature to create CSS Selectors using substrings. There are three ways in which CSS Selectors can be created based on the mechanism used to match the substring.
Types of CSS Selector by Sub String
All the underneath mechanisms have symbolic significance.
Match a prefix
Match a suffix
Match a substring
Let us discuss them in detail.
6.4.1. Match a prefix
It is used to correspond to the string with the help of a matching prefix.
Syntax
[attribute^=prefix of the string]
^ Symbolic notation to match a string using prefix.
Prefix – It is the string based on which match operation is performed. The likely string is expected to start with the specified string.
For Example: Let us consider “Password textbox”, so the corresponding CSS Selector would be:
css=input#Passwd[name^=’Pass’]
6.4.2. Match a suffix
It is used to correspond to the string with the help of a matching suffix.
Syntax
[attribute$=suffix of the string]
# Symbolic notation to match a string using suffix.
The suffix – It is the string based on which match operation is performed. The likely string is expected to ends with the specified string.
For Example, Lets again consider “Password textbox”, so the corresponding CSS Selector would be:
input#Passwd[name#=’wd’]
6.4.3. Match a substring
It is used to correspond to the string with the help of a matching substring.
Syntax
[attribute*=sub string]
* Symbolic notation to match a string using sub string.
Sub string – It is the string based on which match operation is performed. The likely string is expected to have the specified string pattern.
For Example, lets again consider “Password textbox”, so the corresponding CSS Selector would be:
input#Passwd[name*=’wd’]
6.5. CSS Selector by Inner text
The inner text helps us identify and create CSS Selector using a string pattern that the HTML Tag manifests on the web page.
Consider, “Need help?” hyperlink present below the login form at gmail.com.
The anchor tag representing the hyperlink has a text enclosed within. Thus this text can be used to create a CSS Selector to access the designated web element.
Syntax:
html_tag:contains(text)
: – The colon sign is used to symbolize contains method
Contains – It is the value of a Class attribute which is being accessed.
Text – The text that is displayed anywhere on the web page irrespective of its location.
7. Link Selector Locator in Selenium WebDriver
7.1. Link text selector
In order to access links using link text in Selenium, the below-referenced code is used:
driver.findElement(By.linkText("OnlyFullStack Terms and Conditions"));
Note: In a scenario where multiple links have similar text exists, it will automatically select the first one.
7.2. Partial Link text selector
In order to access links using partial link text in Selenium, the below-referenced code is used:
driver.findElement(By.partialLinkText("OnlyFullStack"));
Lets go to our next tutorial where we will discuss below points :
Part 3 – Selenium WebDriver Commands
– Types of Selenium WebDriver Commands
– Selenium WebDriver Commands are divided into 3 types as below
– 1. Browser Commands
– 1. Get Command
– 2. Get Title Command
– 3. Get Current URL Command
– 4. Get Page Source Command
– 5. Close Command
– 6. Quit Command
– 2. Navigation Commands
– 1. Navigate To Command
– 2. Forward Command
– 3. Back Command
– 4. Refresh Command
– What is Web Element?
– 1. Send Keys Command
– 2. Clear Command
– 3. GetText Command
– 4. Submit Command
– 6. Click Command
Source Code
You can find the complete source code on below GitHub repository –
https://github.com/onlyfullstack/selenium-tutorial
Selenium Tutorial
https://www.onlyfullstack.com/selenium-webdriver-tutorial/