0% found this document useful (0 votes)
29 views

Selenium Automation

Selenium is an open source tool that can be used to automate testing of web applications across different browsers and platforms. It supports various programming languages and allows testing browser-based applications without using a graphic user interface. The Selenium WebDriver API is commonly used for robust browser automation by controlling the browser using code. It works by converting code into JSON commands that are sent to a browser's WebDriver, which then communicates with the actual browser to perform actions.

Uploaded by

pulkit0795
Copyright
© © All Rights Reserved
Available Formats
Download as KEY, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Selenium Automation

Selenium is an open source tool that can be used to automate testing of web applications across different browsers and platforms. It supports various programming languages and allows testing browser-based applications without using a graphic user interface. The Selenium WebDriver API is commonly used for robust browser automation by controlling the browser using code. It works by converting code into JSON commands that are sent to a browser's WebDriver, which then communicates with the actual browser to perform actions.

Uploaded by

pulkit0795
Copyright
© © All Rights Reserved
Available Formats
Download as KEY, PDF, TXT or read online on Scribd
You are on page 1/ 87

Selenium

Instructor- Dr. Mukesh Mann


Department of CSE,IIIT Sonepat
Introduction to Selenium

It is open Source tool , Any one can download it free of cost unlike QTP which is paid
and before selenium came to market it was QTP is used to automate test cases.. QTP
FEE IS VERY HIGH.

Its is exclusively used for automation of web browser based application and not
desktop application. And it supports multiple browsers such as chrome, Edge, Firefox ,
IE, safari.

It works with multiple platforms . – windows, Linux, Mac,

we can write or code in multiple languages such as – Java, Python, C#, JavaScript php
, Ruby.
What is difference between Selenium and WebDriver

Selenium is suite of tools to automate web browsers across many platforms. As it


comes up with many tools and one of the tool is webdriver and another is IDE

IDE- is just a record and playback tool, no one uses this because it is just record
and play tool ( used by people having very less knowledge of programming
languages) and therefore everyone uses

Webdriver- is used to create robust browser based automation,

Initial version of selenium was released with two tools – IDE and Selenium remote
control but later the RC name was changed to webdriver. And RC no longer
supports new versions of web browsers.

The only tool we will focus is WebDriver tool in Selenium.


Selenium WebDriver Architecture

We need an editor to write our code suppose we uses eclipse as an editor to write our
selenium, In this editor we need to write our code in my favorite programming language
code such as Java, Python,etc.

After that when you run( trigger ) this Test code , first the complete java code is ( call it
client) is converted into Json format.
Now this Json format is sent to server ( a server is nothing more than a browser driver)
using HTTP PROTOCOL
Selenium WebDriver Architecture

But what is a browser driver ?


Every web browser has its server called browser web driver , say you wish to
automate in chrome than chrome has its own server called chrome web driver.
Once this Json format reaches to respective driver (in client code we have called
chrome driver, thus , Json format will reach to chrome driver only), then it
communicates with its respective browser ( which is obviously chrome in this case as
the driver where the Json format has been received is chrome driver).
Selenium WebDriver Architecture

For e.g., say our client code has line which says open chrome and click on a url , then
this code is first converted into Json and then it is sent to chrome driver which then
interprets this Json format and then perform the actions on the chrome browser. In
response whatever the actions are performed in chrome browser are responded back to
chrome driver which again convert it to Json format and sent back this Json format to
our client code and we can see the output on our client terminal.
You can find web drivers corresponding to different web browsers on internet ( it is
madatory)
Steps to Run First Selenium program

1. Install Java and Set Java Home Path in System variables.


2. Install Eclipse and Create new Marven Project with selenium Dependencies.
3. Understand creation of webdriver object and its related classes
4. Run the First Selenium WebDriver Program with Browser
5. Different ways of setting Browser Driver Executables files.
Steps to Run First Selenium program- Install Java and Set Java Home Path in System
variables

https://www.oracle.com/java/technologies/javase/jdk11-archive-downloads.html
1.

2.

3.

4.

5.

6. In My system the Java path is here - C:\Program Files\Java\jdk-14.0.2


7.

8. Go the Advance System Setting , click on Environmental Variables


9. In System Variables click new
10. Set variable name= JAVA_HOME
11. Path = C:\Program Files\Java\jdk-14.0.2
12.

13. This will set your java path


14. Now download Eclipse, in which we will actually write our code in JAVA
15. https://www.eclipse.org/downloads/
16. Choose option – Download packages -> Eclipse IDE for Java Developers
17.

18. Now click on installed eclipse and while opening it will ask for
19. Set a directory for Workspace
Steps to Run First Selenium program- Install Java and Set Java Home Path in System
variables

1. Now click on installed eclipse and while opening it will ask for
2. Set a directory for Workspace set it as shown-
3.

4. All your projects related to selenium now will be in C:\Users\Mann\


SeleniumTutorials.
Steps to Run First Selenium program- Install Java and Set Java Home Path in System
variables
1. Now a screen will open  click on hide and it will start with following screen
Steps to Run First Selenium program- Install Java and Set Java Home Path in System
1. Asvariables
we know that we can write in different laguages in Eclipse, Lets start with JAVA.
2.

3. File-> New-> JavaProject


4. Write Name of project say
5. :- Introduction
Steps to Run First Selenium program- Install Java and Set Java Home Path in System
1. Asvariables
we know that we can write in different laguages in Eclipse, Lets start with JAVA.
2.

3. If it will ask for creation of module- info java- Uncheck it as we do not wish to cerate and
module based project
Steps to Run First Selenium program- Install Java and Set Java Home Path in System
1. Asvariables
of now this project does not have any information about Selenium, So we need to give
knowledge about selenuim , For that we will take help of Maven ( a central repository for
Java based projects). Say Selenium Team had developed one selenium based library. So
they will host that library in Maven
Steps to Run First Selenium program- Fetching Selenium through Maven central Repository
1. As wee need selenium in Eclispe , so we need to fetch it from Maven central Repository as –
2. https://mvnrepository.com/
3. Search Selenium and download Selenium Java click on this ,  now click on any latest version ,
say 4.3.0. You will get a pop up , Copy the dependency shown on the page.
4. When we paste these four lines of code in our project then it will scan these four line of code and
it will detect that there is something from maven repository .com and it will connect to Marven
repository and it will download all Jar files corresponding that need to be added into the projects .

<!-- https://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-java -->


<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.3.0</version>
</dependency>
Steps to Run First Selenium program- Fetching Selenium through Maven central Repository
1. When we paste these four lines of code in our project then it will scan these four line of
code and it will detect that there is something from maven repository .com and it will
connect to Marven repository and it will download all Jar files corresponding that need to
be added into the projects .
Converting Java Project into Maven project

Since the Java Project need to be have selenium for which we need to copy and paste
these four lines of code that will fetch selenium Jar files into your project through Maven
central repositry therefore we first need to convert out java project int Maven project .
Right click on project window  Configure convert to Maven Project
Now you just need to supply some sensible group id and Artifacts ID , note that these two
things were also there in dependencies four lines and it actually uniquely identify your
project over central repository.

Once you click finish , you will see a pom.xml file in your project , and this is the file
where you will give details about the dependency file, you can put multiple dependencies
in this file by just writing <dependencies> Main file of dependency you wish to fetch <\
dependencies> after <version> in pom.xlm file.
Converting Java Project into Maven project
Once you click finish , you will see a pom.xml file in your project , and this is the
file where you will give details about the dependency file, you can put multiple
dependencies in this file by just writing <dependencies> Main file of dependency
you wish to fetch <\dependencies> after <version>0.0.1-SNAPHOTS in pom.xlm
file.
The moment you will insert
dependency into pom file, a
folder gets created in the
project with name Maven
Dependencies.
If it is not created then follow
following steps –
Right click on project->
maven update  Force
updates of sanphots./
release
In similar way Download another dependency - TestNg

This repository has number of assertions which help us to perform fucntional


testing and matchig expected and actual outputs in out tests

<!-- https://mvnrepository.com/artifact/org.testng/testng -->


<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.6.1</version>
<scope>test</scope>
</dependency>
Lets Install chrome Drivers into the selenium

As we know that Chrome Driver is a tool that is provided by selenium to run the
client code on the chrome browser, Thus we need to first install it as Selenium has
already been installed.

Steps to install chrome Driver –


First go to your browser help  note down chrome browser build number
Now go to https://chromedriver.chromium.org/downloads and download chromedriver
corresponding to your browser build number.
Save it at your project location , In my case it is at C:\Users\Mann\
SeleniumTutorials\chromedriver
Click on src file in project new class- add public static void main and finish.
Lets Install chrome Drivers into the selenium

Now write ChromeDriver driver= new


ChromeDriver(); in main () function , and you will see
that there are few errors underlined as red , this is
because we need to tell SeleniumIntroduction class
form where the ChromeDriver class came from.
Thus mouse over to left side ChromeDriver class and
then you will see an option to import
import org.openqa.selenium.chrome.ChromeDriver;
Chrome Browser has ChromeDriver has methods

Now the class SeleniumInroduction has knowledge from where we get the class
ChromeDriver.
Now using ChromeDriver Class we can automate the Chrome browser. Note that
ChromeDriver is a class, so it has many methods through which we will performs
different tasks and the beauty is that these methods are same in all the classes
for different web browsers. Thus a methods say click() in ChromeDriver class will
click on a url , the same methods with same name comes with other browser’s
drivers so we do not need to learn methods name separately for different
webdriver.
Tus we first created an object of ChromeDriver class called “”driver” and using
this object we can access different methods present in the ChromeDriver class.
WebDriver is an Interface or a Tool

As we now know that different Drivers classes for different browsers have same methods with same name and perform same
functionalities corresponding to their browser. Now how dos all these different Driver Classes for different web Browsers follows this
contract of providing the same methods?

There is an agent sitting over top of all these WebDriver Classes that directs these classes what to do and what rules to follow. In
response these classes follows the directions from this agent . This agent is what we called as Interface.

In selenium we get our tool called – WebDriver, But note that this webdriver is actually an Interface.
Webdriver will just provide names of different methods such as – close(), Quit(), findEement()… etc.
It is the responsibility of different classes ( for different browsers) to implements these methods.
For e.g, ChromeDriver, ChromiumDriver, EdgeDriver, EventFiringWebDriver, FirefoxDriver, InternetExplorerDriver, OperaDriver,
RemoteWebDriver, SafariDriver are all classes, the methods declared by the interface- WebDriver will be implemented by each of these
classes .

And that’s why we need to write following line because ChromeDriver class is now implememting all the methods provided by WebDriver
Class.
public class SeleniumIntroduction implements WebDriver{
public static void main(String[] args) {
// TODO Auto-generated method stub
ChromeDriver driver= new ChromeDriver();
}
Note that ChromeDriver class agree to implement all WebDriver methods and also its own class
specific methods too. That is
ChromeDriver driver= new ChromeDriver();
will give driver object to access both WebDriver interface methods as well as chrome browser
specific methods but do we really need this . Here driver is calling an inetrnal chrome method
resetInputState();
which is not the Webdriver method , but then if you write same code in Edge/ Firfox browser then it
wil not run there because resetInputState() is an internal method of class ChromeDriver.
Thus, in order to restrcit this we just need to have WebDriver methods being accessible by the
object and not the class’s own methods .
So we simply write

WebDriver.resetInputState();
Restricting driver obj to access only WebDriver methods()
Different methods that an Interface provides
Installation of Chrome Web Driver ( a third party Library) developed by Chrome

We need to first install Chrome Driver so that Selenium will call ChromeDriver which in turn calls
Chrome. Thus, Chrome Web Driver is not provided by selenium and we need to install it from
chrome. Similarly for other browsers you need to install their specific web Drivers such as for Edge
browser – medgedriver is there.

1. Go to chrome help  about note down build number


2. Go to ChromeDriver - WebDriver for Chrome - Downloads (chromium.org) to search build number and
download and place it in your project folder( or anywhere but you need to give path )
3. In my case it is at C:/Users/Mann/SeleniumTutorials/chromedriver.exe
4. Thus set System.setProperty(“Property”, “its value”)

System.setProperty("webdriver.chrome.driver",
"C:/Users/Mann/SeleniumTutorials/chromedriver.exe");

Thus during run time Selenium wil call webdriver.chrome.driver with value
C:/Users/Mann/SeleniumTutorials/chromedriver.exe

And thus this way selenium invoke chrome web driver that will take all of your client code and
invoke chrome browser and performs all the actions defined in code on the chrome browser.
Run this code – Right Click on class File -> run as Java Application will involve chrome
browser
Exercise-2 Open url = http://www.iiitsonepat.ac.in/ and fetch title of the page

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumIntroduction {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/Users/Mann/SeleniumTutorials/chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("http://www.iiitsonepat.ac.in/");}}
Exercise-2 Open url = http://www.iiitsonepat.ac.in/ and get title of the page

Title of page can be shown when


you mouseover over the page.

driver.get("http://www.iiitsonepat.ac.in/");
System.out.println(driver.getTitle());
Complete Code to open an url , get title and close () the current tab opened by Selenium

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class SeleniumIntroduction {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/Users/Mann/SeleniumTutorials/chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("http://www.iiitsonepat.ac.in/");
driver.get("http://www.iiitsonepat.ac.in/academic/curriculum/");
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());
// just close one tab which was initially opend by Selenium webdriver
//driver.close();
// quit will close all associated tabs
driver.quit();
}
}
Running Selenium in Edge Browser

Just download Edge Driver after taking edge build number from About

https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/

Place it in same folder as does for chrome and provide the path – Next slide shows
complete code
Running Selenium in Edge Browser

Just download Edge Driver

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class LauchingEdgeBrowser {
public static void main(String[] args) {
System.setProperty("webdriver.edge.driver", "C:/Users/Mann/SeleniumTutorials/msedgedriver.exe");
WebDriver driver= new EdgeDriver();
driver.get("http://www.iiitsonepat.ac.in/");
driver.get("http://www.iiitsonepat.ac.in/academic/curriculum/");
System.out.println(driver.getTitle());
System.out.println(driver.getCurrentUrl());
driver.close();
//driver.quit();
}
}
Exercise – Do Previous task for all other browsers
Vtiger Application Installation

https://drive.google.com/file/d/1MGJaZvuToittaJQ_jnMskoV2MeihULn8/view?usp=sharing
After Installation put following on url - http://localhost:8888/

User name = admin


Password = admin
What is Locator in Selenium

Locators will help in location the exact position of any Filed such as Edit box, link etc on the page .
For. Eg., you wish that selenium will fill username and password on text box present on Gmail page then
you must specify the exact location of these edit box. Locators helps in locating such address/ exact
location a HTML field on the web page page.

Once loaction is identified , that location is given to selenium code , Selenium will go to that location and
perform action.

Supporting HTML Locators list –

ID
Xpath
CSS Selector
name
Class Name
Tag Name
Link Text
Partial Link Text
Performing Signin to Gmail using Locators

Task- We have to signIn to http://localhost:8888/


where username and password will be asked ( First you need to install Vtiger application
as discussed previously, we will use this application to learn various components of
selenium automation)

if correct user name and password is entered then we will be successfully login else it will
show wrong password on page.
Lets automate this process through Locators-
Suppose we created following credential
user name – admin
Password- admin

Procedure –
In order to locate the username field on the Vtiger page we will right click and inspect the
page  there you will find an arrow select an element in the page to inspect it (Ctrl+shit+c)
{ see left most upper corner of the inspect page), when you click on username on the page
that HTML element corresponding to that username is highlighted in the inspect page.
Lets understand HTML
Structure of User Name field

Various supporting Locators by Selenium are given below and out of these we will look any one of them if it is present
in Username HTML Structure? – Yes there are three, so we can use anyone of them to uniquely identify usernale box
position on the page.

ID
Xpath
CSS Selector
Name
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
Steps
import org.openqa.selenium.chrome.ChromeDriver; 1. Create new java class by right
import org.openqa.selenium.edge.EdgeDriver;
public class Locators {
clicking on src ,
public static void main(String[] args) { Src new class. Name it as
System.setProperty("webdriver.chrome.driver", "C:/Users/Mann/SeleniumTutorials/chromedriver.exe");
WebDriver driver= new ChromeDriver(); locatiorexamples, also select public
driver.get("http://localhost:8888//"); static void main() and click finisgh.
driver.findElement(By.name("user_name")).sendKeys("admin");
driver.findElement(By.name("user_password")).sendKeys("admin");
driver.findElement(By.id("submitButton")).click();
}
}
Exercise - Identify among supporting tags ( shown in Blue) , which one can be used to fill
username in Gmail login page
Identify among supporting tags ( shown in Blue) , which one can be used to fill username in
gmail login page
Identify among supporting tags ( shown in Blue) , which one can be used to fill username in
gmail login page – Solution – Four solutions are presented here – id, name, className, tagName
Editable Code

< Input type=”text” name= “user_name”>


Sometime on a page you can see it as (for e.g., in case of Gmail Home page)

The Sequence follows following order


<TagName Attribute = “Value”>
TagName  will identify the Tag of form such as in above case it is Input
Attribute Shown in Red
Green  attribute value; for type as an attribute the value is “text” and “email” respectively in above two HTML form
tag.
For the attribute autofocus the value is not mentioned
You can also find different locators when you mouseover
On any field after you click inspect element.

For Username field on page we select –name , as a locator


and put its value as Username.

For Password field we uses – Name as locator and its value


as Password.
One the next page we have shown the exact sequence of
Filling the username and pwd on our cloud based
Vtiger application
Create a new class file with name Locator and put following code there

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class Locators {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/Users/Mann/SeleniumTutorials/chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("http://localhost:8888//");

driver.findElement(By.name("user_name")).sendKeys("admin");
driver.findElement(By.name("user_password")).sendKeys("admin");
driver.findElement(By.id("submitButton")).click();
}
Enter into vtiger application by specifying correct username and password .

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class Locators {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:/Users/Mann/SeleniumTutorials/chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("http://localhost:8888//");
driver.findElement(By.name("user_name")).sendKeys("admi
n");
driver.findElement(By.name("user_password")).sendKeys("a
dmin"); driver.findElement(By.id("submitButton")).click();
}
Css Selector– Through Css Selector Hub( This plug-in helps in identifying various locators)

Sometime we are not able to identify the position of an element even after specifying the
tagName, id, name individually , The possible reason is that either these locators are
missing in the HTML or more than one HTML line has same locators, Therefore in order to
identify the location of element we will take help of Css selector
Css Selector – is a path made up of more than one locator and uniquely identifythe
poistion of element on HTML element.
Steps to install Selector Hub
Lets first install a chrome plug-in through which we an automatically generate Css
Locator .
Go to Google and type Css Selector Hub plug-in for Chrome and install it Now right click
on webpage or any element you wish to generate Css path
You will find SelectHub copy relative Css Selector
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class Locators {
public static void main(String[] args) {
System.setProperty("webdriver.edge.driver", "C:/Users/Mann/SeleniumTutorials/msedgedriver.exe");
WebDriver driver= new EdgeDriver();
driver.get("http://localhost:8888//");
// Login using id,
driver.findElement(By.name("user_name")).sendKeys("admin");
driver.findElement(By.name("user_password")).sendKeys("admin");
driver.findElement(By.id("submitButton")).click();
// CSS Selector Example - generated by SelectorHub Plugin
driver.findElement(By.cssSelector("#submitButton")).click();
}
}
How to generate Css Selector manually

1. Using Class Name


2. When Class Name is Missing.
3. If HTML has no class and id

Given following HTML Code generate CSS Selector

<div class="input"><input type="text" name="user_name"></div>

If you have a ClassName and you wish to drive Css out of it then write it as
Class Name- tagname.classname

Css will be - div. input

driver.findElement(By.className("div.input")).click();
2. When Class Name is Missing.
Here there is no class name, even you can build css
E.g.- <input type="hidden" name="return_module" value="Users">
Css will be – tagName#attrubuteValue  input# return_module
First Way
driver.findElement(By.cssSelector("input#return_module")).click();
Second way is –
driver.findElement(By.cssSelector("input#Users")).click();
Third Way
driver.findElement(By.cssSelector("input#hidden")).click();
3. If HTML has no class and id
Syntax is -
TagName[attribute=’Value’]
Here we do not have any class and id
E.g.- <input type="hidden" name="return_module" value="Users">
Css Selector
input.[ value=’Users’>]
driver.findElement(By.cssSelector("input.[value='Users']")).click();
EFFECTIVE CSS SELECTORS

Back to Basics
Formulating a CSS selector is defined by this algorithm:

element[attribute(*|^|$|~)='value']

The element portion will be what element you are selecting. The attribute portion will be
what attribute you are selecting on. The (*|^|$|~) portion is an optional comparison operator
depending on what you need (put link here)
KISS (Keep it Simple Stupid)

Any element that you want is able to be selected using CSS. It’s important to keep in mind to
keep it simple. One reason to even use css is the simplicity. Consider the following:

1 <input type="text" name="username" />


To select this, we have several options.
1. We can match by the type attribute. e.g: input[type='text'] but is this really effective? What
if we have more elements than that one. That CSS selector would select an array of all
elements that have the type attribute set to “text”.
2. We can match by the name attribute. e.g: input[name='username']. Now this would be
absolutely unique (assuming there is no more elements on the page with the
name=’username’)
EFFECTIVE CSS SELECTORS

The 2 Unique Attributes


In order, there is:
1. id

2. name

For selecting unique elements, and semantically, these are the three top attributes that
can be selected with 95% certainty.

Consider the following:


1 <input type="text" id="username_field" name="username" />
This is an excellently designed element because it has both
the id and name attributes. Unnecessary? Maybe, but we aren’t complaining.

Using CSS Selectors, we can match on either the id or name attribute because these
two attributes are the top 2 unique attributes to match on. So our selectors could be:
3. input[id='username_field']

4. input[name='username']

or even
1 input[id='username_field'][name='username'] /*(for ultimate uniqueness.)*/
EFFECTIVE CSS SELECTORS

In a page that contains hundreds of elements, a css selector


like [name='something'] will scan ALL of the elements on the page to find an
attribute name that equals something.

In that same page, input[name='something'] will scan ONLY THE INPUT


ELEMENTS for the name attribute that equals "something". It’s purely subjective,
but it also helps with anybody else that looks at your code. It’s obvious what type of
element you are selecting.
Shorthand
In CSS, there are only 2 shorthand selectors. These selectors are:
1. id

2. and class
Both of these attributes can be matched very easily using their respective
shorthand symbol. Consider the following for id:
<input type="text" id="username_field" name="username" />
From our selector above (input[id='username_field']).. This can be simplified using a
shorthand selector to:
1 input#username_field
EFFECTIVE CSS SELECTORS

As you can see from above, the hash (#) symbol is the shorthand symbol for
the id attribute.

input[id='username_field'] === input#username_field

For class, consider the following:

1 <a href="#" class="home-link link bold" />


From that field above, we can use the selector:

1 a[class='home-link link bold']

but what if the class is dynamic? What if the web app adds a new class?
The class attribute will no longer equal that. If we use the shorthand: a.home-
link.link.bold

We can be sure that we will still select it even if they add a class to it. This is the
shorthand for:
1 a[class~='home-link'][class~='link'][class~='bold']
EFFECTIVE CSS SELECTORS

Comparison operators
There are only a few comparison operators that are in existance and should all be
memorized.
1. Equals (=)

2. Starts with (^=)

3. Ends with ($=)

4. Contains (*=)

5. Contains in a list (~=)

“Equals (=)” operator


This operator will be used when an attribute is static. For example: <input
id="username" />; The "username" value is static, therefore = should be used for
the comparison.
EFFECTIVE CSS SELECTORS

“Starts with (^=)” operator

Consider the input that was mentioned above. What if the page is dynamically generated
and it ensured that each ID is unique and there was no duplication? What would happen,
is that page generator would use some dynamic number or string of characters and
concatenate that to the id.

For example:
<a href="#" id="link_1" />

Ask yourself, what is going to always be the same.

since the 1 in the attribute value is dynamic, we can say that link will be static. And
since the id Starts With link, let’s match on that using the Starts With (^=) selector:
a[id^='link'] means id starts with ‘link’.

“Ends with ($=)” operator

This operator can be particularly useful when you have dynamic attributes similar to the
element above
EFFECTIVE CSS SELECTORS

“Ends with ($=)” operator

This operator can be particularly useful when you have dynamic attributes similar
to the element above. Consider the following html:
1. <a href="#" id="link_1"
2. <a href="#" id="link_12323aasdf_something" />

Unfortunately with these two elements when we want to select the second
element, won’t work with just a[id^='link'] because that would not be unique
enough. What we can do, is utilize the ends with ($=) CSS operator. Thus for <a
href="#" id="link_12323aasdf_something" /> the CSS Selector will be
1 a[id^='link'][id$='something']
Here we can actually combine the two different selectors! This is a sure way to
make sure we select the element we need.

“Contains (*=)” operator


EFFECTIVE CSS SELECTORS

“Contains (*=)” operator

This is one of the most frequently used operator, and can be used for many
different purposes. It’s quite simple..
We just find an element that has an attribute that contains something
1 <div id="12345_my-div_abcde" />

For arguments sake, let’s say that the 12345 and the abcde are dynamic,
therefore we can’t use Starts with, or Ends with. In this case, we would
use contains!

1 div[id*='my-div']
EFFECTIVE CSS SELECTORS

“Contains in a list (~=)” operator


This is the single most operator that is underrated in CSS. Most people will go
right above it by using the contains operator, but is that really the best option?

Lets start by defining what this selector does.

The ~= selector will find the attribute that you specify, and will look for
something in a list that is SPACE SEPERATED. This is most particularly applied to
the class attribute since we usually specify something like:
1 <div class="class1 class2" />
So in essence:
1 div[class~='class1'][class~='class2']
is the EXACT same as:
1 div.class1.class2
It will not care where the words are, but as long as the words are separated
by spaces, then it will find what you need.
Practical Examples
Formula -
<div class="input"> element[attribute(*|^|$|~)='value']
<input type="text" name="user_name"></div>

Identify Username Filed on Vtiger Home page using CSS Selector using various Css Selectors -
Practical Examples- Solution
Formula -
<div class="input"> element[attribute(*|^|$|~)='value']
<input type="text" name="user_name"></div>

System.setProperty("webdriver.edge.driver", "C:/Users/Mann/SeleniumTutorials/msedgedriver.exe");
WebDriver driver = new EdgeDriver();
//driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
driver.get("http://localhost:8888//");
//driver.findElement(By.name("user_name")).sendKeys("admin");// Supply wrong user and Password
//driver.findElement(By.name("user_password")).sendKeys("admin");
//driver.findElement(By.cssSelector("input[type='text']")).sendKeys("admin");
//driver.findElement(By.cssSelector("input[name='user_name']")).sendKeys("admin");
//driver.findElement(By.cssSelector("input[type='text'][name='user_name'] ")).sendKeys("admin");
//driver.findElement(By.cssSelector("input[name^='user']")).sendKeys("admin");
//driver.findElement(By.cssSelector("input[name^='user'][name$='name']")).sendKeys("admin");
driver.findElement(By.cssSelector("input[name*='_name']")).sendKeys("admin");
Practical Examples
Formula -
<div class="input"> element[attribute(*|^|$|~)='value']
<input type="text" name="user_password"></div>

Identify Password Filed on Vtiger Home page using CSS Selector


using various Css Selectors -
Practical Examples
Formula -
<div class="input"> element[attribute(*|^|$|~)='value']
<input type="text" name="user_password"></div>

Identify Submit Button Filed on Vtiger Home page using various


Css Selectors -
System.setProperty("webdriver.edge.driver", "C:/Users/Mann/SeleniumTutorials/msedgedriver.exe");
WebDriver driver= new EdgeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
driver.get("http://localhost:8888//");
// Login using id,
driver.findElement(By.name("user_name")).sendKeys("admin");// Supply wrong user and Password
driver.findElement(By.name("user_password")).sendKeys("admin");
//driver.findElement(By.id("submitButton")).click();
// System.out.println(driver.findElement(By.cssSelector("div.errorMessage")).getText());
//driver.findElement(By.cssSelector("input.[value='Login']")).click();
// Methods - 1 CSS selectors - TagName#Value
//driver.findElement(By.cssSelector("input#submitButton")).click();
driver.findElement(By.cssSelector("input.[value='submitButton']")).click();
Complete Code – Try to observe the output by Uncommenting following code

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class Locators {
public static void main(String[] args) {
System.setProperty("webdriver.edge.driver", "C:/Users/Mann/SeleniumTutorials/msedgedriver.exe");
WebDriver driver= new EdgeDriver();
driver.get("http://localhost:8888//");
// Login using id,
driver.findElement(By.name("user_name")).sendKeys("admin");
driver.findElement(By.name("user_password")).sendKeys("admin");
driver.findElement(By.id("submitButton")).click();
// CSS Selector Example - generated by SelectorHub Plugin
// driver.findElement(By.cssSelector("#submitButton")).click();
// Using id when no class is present
//driver.findElement(By.cssSelector("input#hidden")).click();
// Using ClassName
// driver.findElement(By.className("div.input")).click();
// When no class and no id is present
//driver.findElement(By.cssSelector("input.[value='Users']")).click();
}}
Various Ways to generate Css Path as discussed in previous slides
Important Points Regarding Locator and its creation

1. Selenium scans entire web page from Top to Left and if there are two classes with same name then whichever
will come first during scanning will be taken and rest will be ignored.
2. Sometime same attribute value is used at number of places in HTML so you need to be careful that you have
created unique locator which identify exact position of element – Recommended to use Selector Hub plug-in.
3. Another way to copy css path is
4. Right click on the element  Inspect  highlight the html corresponding to the element  right click and copy as
Selector .
5.
Exercise Get what is displayed when you enter wrong user name and password on Login
button

System.out.println(driver.findElement(By.cssSelector("input.[value='Users']")).getText());
Although the css selector is right still we get an error sometimes and the text will not be displayed on the
screen because it took some time to display the message on the console but selenium immediately Signin
into the Vtiger
So we can use wait function to observe the output on the console
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
System.out.println(driver.findElement(By.cssSelector("div.errorMessage")).getText());
You must specify a valid username and password. Will be displayed on console
You can also check if the selector that you have made is there or not by using console and writing your selector there Come to console > $
(‘write your css’) You can see the corresponding HTML , you can click and expand it to see how many elements are there corresponding to
your CSS – here you can see that there is one element - It indicates that this message should be displayed when you try to print it
You can also check if the selector that you have made is there or not by using console and writing your selector there Come to console > $
(‘write your css’) You can see the corresponding HTML , you can click and expand it to see how many elements are there corresponding to
your CSS – here you can see that there is one element - It indicates that this message should be displayed when you try to print it
In case of xpath you need to put x after $ and then specify your xpath as –>$x('//div[@class="errorMessage"]') You can see the corresponding HTML , you can click and expand it to see how many
elements are there corresponding to your CSS – here you can see that there is one element - It indicates that this message should be displayed when you try to print it
Fully Executable Code – Try to Run it in Eclipse
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class Css_SelectorusingConsole_5 {
public static void main(String[] args) {
System.setProperty("webdriver.edge.driver", "C:/Users/Mann/SeleniumTutorials/msedgedriver.exe");
WebDriver driver = new EdgeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
driver.get("http://localhost:8888//");
// Login using id,
driver.findElement(By.name("user_name")).sendKeys("admin1");// Supply wrong user and Password
driver.findElement(By.name("user_password")).sendKeys("admin1");
driver.findElement(By.id("submitButton")).click();
// Two ways to captureError message displayed on Screen "You must specify a valid username and password."
// Use Selector Hub to identify the css or xpath
// First way - Using css Selector
//System.out.println(driver.findElement(By.cssSelector("div.errorMessage")).getText());
// OR USING SELECTOR HUB THE RELATIVE PATH GENERATED IS - .errorMessage
// System.out.println(driver.findElement(By.cssSelector(".errorMessage")).getText());
// Second way - Using xpath Selector
System.out.println(driver.findElement(By.xpath("//div[@class=\"errorMessage\"]")).getText());
}
}
Selecting xpath using parent child relationship between html tags

Lets suppose you wish to eneter username , then you have to traverse upto this using
parent child relatiosnhip as –

driver.findElement(By.xpath("/html[1]/body[1]/div[1]/table[1]/tbody[1]/tr[1]/td[2]/div[1]/
form[1]/div[1]/div[2]/input[1]")).sendKeys("admin1");

import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class Css_SelectorusingConsole_5 {
public static void main(String[] args) {
System.setProperty("webdriver.edge.driver", "C:/Users/Mann/SeleniumTutorials/msedgedriver.exe");
WebDriver driver = new EdgeDriver();
//driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
driver.get("http://localhost:8888//");
// Login using id,
driver.findElement(By.xpath("/html[1]/body[1]/div[1]/table[1]/tbody[1]/tr[1]/td[2]/div[1]/form[1]/div[1]/div[2]/input[1]")).sendKeys("admin1");
driver.findElement(By.name("user_password")).sendKeys("admin1");
driver.findElement(By.id("submitButton")).click();
System.out.println(driver.findElement(By.xpath("//div[@class=\"errorMessage\"]")).getText());
}}
Link Text Locator

When you wish to click on a link in HTML we can use it but make sure that the HTML code of that text link should
contain <a> as anchor tag

<a href="http://www.vtiger.com/products/crm/privacy_policy.html" target="_blank">Privacy Policy</a>


// Clicking on any link on HTML using LinkText
driver.findElement(By.linkText("Privacy Policy")).click();
Generating Xpath -

Generating Xpath - Both Css and Xpath are generic Locator and we do not need specific property of HTML to
generate them ]

Syntax
//tagName[@attribute=’value’]
<input type="submit" id="submitButton" value="Login"> Xpath will be
// input[@id='submitButton‘]
driver.findElement(By.xpath("// input[@id='submitButton']")).click();
Sample Code to Practice – Copy and sate Eclipse and Observe the outputs
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
public class Locators {
public static void main(String[] args) {
System.setProperty("webdriver.edge.driver", "C:/Users/Mann/SeleniumTutorials/msedgedriver.exe");
WebDriver driver= new EdgeDriver();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
driver.get("http://localhost:8888//");
// Login using id,
driver.findElement(By.name("user_name")).sendKeys("admin");
driver.findElement(By.name("user_password")).sendKeys("admin");
//driver.findElement(By.id("submitButton")).click();
// CSS Selector Example - generated by SelectorHub Plugin
// driver.findElement(By.cssSelector("#submitButton")).click();
// Using id when no class is present
//driver.findElement(By.cssSelector("input#hidden")).click();
// Using ClassName
// driver.findElement(By.className("div.input")).click();
// When no class and no id is present
//driver.findElement(By.cssSelector("input.[value='Users']")).click();
// Get Text of login Button and display on Console
//System.out.println(driver.findElement(By.cssSelector("div.errorMessage")).getText());
// Clicking on any link on HTM using LinkText
//driver.findElement(By.linkText("Privacy Policy")).click();
//clicking on Login Button using xpath
driver.findElement(By.xpath("// input[@id='submitButton']")).click();
}}
Sign-out from Application

// Sign Out from the application


driver.findElement(By.linkText("Sign Out")).click();
/ Clearning the username
driver.findElement(By.name("user_name")).clear();
Regular Expressions – Code file – regularExpressions_3

Some times in HTML the developer defines more than one class name ( that’s is class input has more than omne
name
Here the email or phone number in Gmail has following HTML STRUCTURE
<input type="email" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="username"
spellcheck="false" tabindex="0" aria-label="Email or phone" name="identifier" autocapitalize="none"
id="identifierId" dir="ltr" data-initial-dir="ltr" data-initial-value="" badinput="false" aria-invalid="true">

You cans see hat the input class attribute is composed of more than one name - whsOnd zHQkBf

In order to frame css path for this we can use regular expression as –
*  perform a partial match with the class attribute value. The css value shall be input[class*= whsOnd]
This means the subtext whsOnd is present in the actual text whsOnd zHQkBf
^  perform a match with the class. The css value shall be input[class^= ‘whsOnd’]. This means the actual
text whsOnd zHQkBf starts with the subtext whsOnd.
$ perform a match with the class. The css value shall be input[class$=’zHQkBf’]. This means the actual
text whsOnd zHQkBf ends with the subtext zHQkBf.
Code for regular Expressions

For each of these three regular expression usages the code will look as –
Using *
driver.get("https://accounts.google.com/");
driver.findElement(By.cssSelector("input[class*= whsOnd]")).sendKeys("admin");

Using ^
driver.get("https://accounts.google.com/");
driver.findElement(By.cssSelector("input[class^='whsOnd']")).sendKeys("admin");

Using $
driver.findElement(By.cssSelector("input[class$='zHQkBf']. ")).sendKeys("admin");
Writing Test Case using Assertion

Remember that in poem file we have used TestNg Dependency which is having lot
of assertion to work with.
An assertion is used to compare two text with each other

Write a test case to compare the text appear on the screen after login to vtiger
Talk No- 20use of Selector Hub

In this Tutorial we will learn about the use of Selector Hub to identify the xpath
Use of selector Hub to automatically find xpaths
Open browser  open localhost:8888 inspect element  click left most upper corner to inspect element 
now right click on page  select selector hub and copy different xpaths --

You might also like