Selenium Automation
Selenium Automation
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.
we can write or code in multiple languages such as – Java, Python, C#, JavaScript php
, Ruby.
What is difference between Selenium and WebDriver
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
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.
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
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
https://www.oracle.com/java/technologies/javase/jdk11-archive-downloads.html
1.
2.
3.
4.
5.
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.
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 .
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
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.
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.
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
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
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/
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.
ID
Xpath
CSS Selector
name
Class Name
Tag Name
Link Text
Partial Link Text
Performing Signin to Gmail using Locators
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
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
If you have a ClassName and you wish to drive Css out of it then write it as
Class Name- tagname.classname
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:
2. name
For selecting unique elements, and semantically, these are the three top attributes that
can be selected with 95% certainty.
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
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.
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 (=)
4. Contains (*=)
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" />
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’.
This operator can be particularly useful when you have dynamic attributes similar to the
element above
EFFECTIVE CSS SELECTORS
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.
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
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>
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
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
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 --