Selenium Notes
Selenium Notes
Selenium Notes
Login Rediffmail:
package Automation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
//X-path
/*driver.findElement(By.xpath("//*[@type='text']")).sendKeys("anees");
driver.findElement(By.xpath("//input[contains(@name,'pass')]")).sendKeys("test1234");
driver.findElement(By.xpath("//input[@title='Sign in']")).click();*/
//css
//driver.findElement(By.cssSelector("input[type='text']")).sendKeys("anees");
//driver.findElement(By.cssSelector("input[type*='pass']")).sendKeys("test1234");
//driver.findElement(By.cssSelector("#password")).sendKeys("test1234");
//driver.findElement(By.cssSelector("input#password")).sendKeys("test1234");
//driver.findElement(By.cssSelector("input.signinbtn")).click();
}
2
Multiple Logins:
package Automation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
}
3
}
Static Dropdown
Inbox
package Automation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.Select;
driver.get("https://book.spicejet.com/");
driver.manage().window().maximize();
currdropdown.selectByVisibleText("GBP");
String z = currdropdown.getFirstSelectedOption().getText();
System.out.println(z);
Xpath
tagName[@attribute='value']
//*[@attribute=’value’]
//tagName[contains(@attribute,'value')]
4
Css-
tagName[attribute='value']
tagName#id
#id
tagName.classname
tagName[attribute*='value']
Absolute XPath
/html[1]/body[1]/div[1]/div[1]/div[1]/div[2]/form[1]/div[1]/div[2]/div[2]/div[2]/div[1]/
input[1]
package Automation;
import javax.swing.plaf.basic.BasicTableHeaderUI;
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 java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
5
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
if (singleoption.getText().equals(checkboxdiscount))
{
switch (singleoption.getText())
{
case "Student":
driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchVi
ew_Student")).click();
break;
default:
System.out.println("no discount group available");
break;
}
break;
}
---------------------
package Automation;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
7
import org.openqa.selenium.chrome.ChromeDriver;
if (Firstheader.equals("October 2022"))
{
driver.findElement(By.xpath("//td[contains(@class,'ui-datepicker-current-day
')]")).click();
}
}
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
8
/*
First we need to check If oneway is selected then only Departdate should be enabled.If
Round trip is selected then both the
Depart date and Return date should be enabled
To Identify Enable and Disable element
In general, if the element is disabled, upon click on element nothing should happen.
In latest technology though the UI field looks like disabled, it is not actually disabled. Still we
can click on this to open.
For this type of scenarios, is enabled method will not work. We need to get the Attribute
value of the element which is making
it look like disabled and verify it.
*/
}
9
else
if(driver.findElement(By.id("ControlGroupSearchView_AvailabilitySearchInputSearchView_R
oundTrip")).isSelected()==true)
{
String returnDatafielddisplay =
driver.findElement(By.id("marketDate_2")).getAttribute("style");
System.out.println(returnDatafielddisplay);
if (returnDatafielddisplay.contains("1"))
{
System.out.println("ReturnDate field is enabled");
}
else
{
System.out.println("ReturnDate field is disabled");
}
}
}
}
Calender - selecting specific date
package Automation;
import java.util.List;
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;
{
String Fisrstheader=driver.findElement(By.xpath("//div[contains(@class,'ui-
datepicker-group-first')]/div/div")).getText();
System.out.println(Fisrstheader);
String Secondheader=driver.findElement(By.xpath("//div[contains(@class,'ui-
datepicker-group-last')]/div/div")).getText();
System.out.println(Secondheader);
if (Fisrstheader.equals(reqmonth))
{
List<WebElement> alldays =
driver.findElements(By.xpath("//div[contains(@class,'ui-datepicker-group-first')]
//a[contains(@class,'ui-state-default')]"));
System.out.println(alldays.size());
else if (Secondheader.equals(reqmonth))
{
List<WebElement> alldays =
driver.findElements(By.xpath("//div[contains(@class,'ui-datepicker-group-last')]
//a[contains(@class,'ui-state-default')]"));
System.out.println(alldays.size());
}
break;
}
11
else
{
driver.findElement(By.xpath("//span[contains(@class,'ui-icon-circle-triangle-
e')]")).click();
}
}
}
}
mousehover actions
package Automation;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
driver.get("https://www.amazon.in");
driver.manage().window().maximize();
}
ALERT
package Automation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
}
package Automation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
}
Drag and Drop
package Automation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
SCREEN SHOT
package Automation;
import java.io.File;
import java.io.IOException;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import com.google.common.io.Files;
15
driver.get("https://www.amazon.in");
driver.manage().window().maximize();
Synchronization:
Synchronization is a process to make both script and the Application under test into sink
There are 4 types of synchronization methods
1. ImplicitWait
2. ExplicitWait
3. Thread.Sleep
4. Fluent wait
Implicit wait is declared globally, if we set 5secs, then it will wait by default 5secs before
throughing error message, it is applicable for all the elements
16
driver.manage().timeouts().implicitlyWait(5,TimeUnit.seconds)
Give Bank transaction example – fund transfer, online payment, mini statement, update
personal info, Bank statement for 1 year
Fluent Wait:
Fluent wait is also a type of explicit wait
Fluent wait finds the web element repeatedly at regular intervals of time until the timeout
or till the element is found
Synchronisation example:
Implicit wait: Implicit wait time is applied on all elements. No need to specify any conditions for
wait.
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Explicit wait: Explicit wait is applied on only one element which is given by us. We need to
specify a condition for that web element before proceeding further in the code.
Fluent wait: Fluent wait is a wait in Selenium in which we can give maximum amount
of time to wait for specific condition with a polling time to check the web element in
regular intervals. We can also configure the wait to ignore any exception during polling period before
throwing “ElementNotVisibleException”.
Excericise:
package Automation;
import java.util.concurrent.TimeUnit;
import javax.xml.datatype.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
17
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.FluentWait;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
//Implicitwait
//driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
/*driver.findElement(By.id("alert")).click();
String alertmsg=driver.switchTo().alert().getText();
System.out.println(alertmsg);*/
//Explicitwait
driver.findElement(By.id("display-other-button")).click();
boolean btn = driver.findElement(By.id("hidden")).isDisplayed();
System.out.println(btn);
//Fluent Wait
FluentWait Wait1 = new FluentWait(driver);
Wait1.withTimeout(50, TimeUnit.SECONDS).pollingEvery(5, TimeUnit.SECONDS);
Window Handle:
If in our project you need to run your script on more than one window, pon
click on some button or link a url might be opened as a tab or new window. In
this case you need to implement window Handles concept. Firstly, we need to
inform driver that you need to getwindowhandles and set those into a string
value. As there are multiple windows we need to iterate among them so we
need to add a statement for iterator. Initially the focus will be outside. We
need to make focus on parent and then child using the statement it.next() and
then you can inform driver to switch its focus to parent or child.
Exercise:
18
package Automation;
import java.util.Iterator;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
driver.switchTo().window(child);
String message =
driver.findElement(By.xpath("//div[@class='text-center']/h1")).getText();
System.out.println(message);
driver.switchTo().window(parent);
driver.findElement(By.xpath("//ul[contains(@class,'nav-stacked')]/
li[2]")).click();
//driver.close();
driver.quit();
*/
driver.switchTo().window(child);
String message1 =
driver.findElement(By.xpath("//div[@class='text-center']/h1")).getText();
19
System.out.println(message1);
iFrame in Selenium Webdriver is a web page or an inline frame which is embedded in another web page. The
iframe is often used to add content from other sources like an advertisement into a web page. The iframe is
defined with the <iframe> tag
Right click on the element, If you find the option like ‘This Frame’ or ‘View Frame source’ or ‘Reload
frame’ then it is an iframe
Right click on the page and click ‘View Page Source’ and Search with the ‘iframe’, if you can find any
tag name with the ‘iframe’ then it is meaning to say the page consisting an iframe.
We can switch over the elements and handle frames in Selenium using 3 ways.
By Index
By Name or Id
By Web Element
Switch to the frame by index: - When there are multiple frames in page, we can switch to
frame in Selenium by using index.
driver.switchTo().frame(0); //int
driver.switchTo().frame(1);
Switch to the frame by Name or ID: - Name and ID are attributes for handling frames in Selenium through
which we can switch to the iframe.
driver.switchTo().frame(“iframe1”); // String
driver.switchTo().frame(“id”);
Switch to the frame by Web Element: - We can even switch to the iframe using web element .
driver.switchTo().frame(WebElement);
Switch back to the Main Frame - we have to come out of the iframe.
To move back to the parent frame, we can either use switchTo().parentFrame() or if you want to get back to the
main frame, you can use switchTo().defaultContent();
driver.switchTo().parentFrame();
driver.switchTo().defaultContent();
To find the total number of iframes present inside the page using the tagname ‘iframe’ –
int size = driver.findElements(By.tagName("iframe")).size();
Exercise:
package Automation;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
20
import org.openqa.selenium.chrome.ChromeDriver;
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Testing");
driver.switchTo().defaultContent();
driver.findElement(By.xpath("//ul[contains(@class,'nav-tabs')]/li[2]")).click();
Framework:
Assertion:
https://mvnrepository.com/artifact/org.testng/testng/6.7
For Assertions, we have a TestNG frame work which we use. Download the TestNG jar
Access this URl à https://jar-download.com/artifacts/org.testng/testng
Click on Download testng.jar and unzip the downloaded file and attach the jar
files to build path
Eg:
Assert.assertTrue(true);
Assert.assertEquals(Actualtextmessage, ExpectedMessage);
21
<test name="Personalloan">
<classes>
<class name="TestAutomation.flexiloan"/>
<class name="TestAutomation.smartloan"/>
</classes>
</test>
<test name="Carloan">
<classes>
<class name="TestAutomation.carBuyloan"/>
<class name="TestAutomation.carleaseloan"/>
</classes>
</test>
</suite>
22
----------------------------
How to exclude few test cases without executing from a class file
Now, assume there are 3 test cases in a class, if you want to run only 1 test case Then you
can exclude other 2 test cases
<?xml version="1.0" encoding="UTF-8"?>
<suite name="LoansDepartment">
<test name="Homeloan">
<classes>
<class name="TestAutomation.mortageloan">
<methods>
<exclude name="mortageloanloginwithWEB"/>
<exclude name="mortageloanloginwithAPP"/>
</methods>
</class>
</classes>
</test>
</suite>
How to execute only specific test cases without executing all test cases from a class file
Now, assume there are 3 test cases in a class, if you want to run only 1 test case Then you
can add include method
-----------------------
Regular Expression:
Now in one Class file if there are 6 test cases related to Web and 2 test cases
related to APP and Branch. If the user want to run only the test cases related to
Web(6 test cases), in this case instad of excluding the oher two test cases, we
can include with regular expression fixedloanloginWeb.*
fixedloanloginweballvalid
fixedloanloginwebvaliduser
fixedloanloginwebinvaliduser
23
fixedloanloginwebinvalidpassword
fixedloanloginwebblank
fixedloanloginAPP
fixedloanloginBranch
--------------------------
How to execute only sanity test cases or only regression test cases
To handle this type of test exection, TestNG framework has comeup with a concept called
“Grouping”
For this we need to add a system like
@Test (groups={“sanity”})
And need to update the TestNG.xml file as below
<?xml version="1.0" encoding="UTF-8"?>
<suite name="LoansDepartment">
<test name="Homeloan">
<groups>
<run>
<include name ="sanity"/>
</run>
</groups>
<classes>
<class name="TestAutomation.carBuyloan"/>
<class name="TestAutomation.carleaseloan"/>
<class name="TestAutomation.fixedloan"/>
<class name="TestAutomation.flexiloan"/>
<class name="TestAutomation.mortageloan"/>
<class name="TestAutomation.smartloan"/>
</classes>
</test>
</suite>
--------------------------
Depends On
24
Now assume a scenario where one test case output should be input from other test case it
means one test case is depended on other test cases to execute. To handle such type of
cases TestNG has a concept called “Depends on Methods”
@Test(dependsOnMethods = {"fixedloanloginwithWEBsplcharuser"})
Assume a scenario where you have 100 test cases in a suite and there is a defect which is
causing 2 test cases to fail. Everyone when you execute the automation suite the both test
cases are failing which s expected due to the open defect. To handle such type of cases
TestNG has a flag/switch called “enabled”
@Test(enabled=false)
Priority Setting:
@Test(priority = 1)
public void CarBuyLoanLoanWEB()
{
System.out.println("CarBuyLoan from WEB");
}
@Test(priority = 2)
public void CarBuyLoanAPP()
{
System.out.println("CarBuyLoan from APP");
Assert.assertTrue(true);
}
@Test(priority = 0)
public void CarBuyLoanBranch()
{
System.out.println("CarBuyLoan from Branch");
}
-----
TestNG Annotation
@BeforeSuite - The @BeforeSuite annotated method will run before the execution of
all the test methods in the suite.
@AfterSuite - The @AfterSuite annotated method will run after the execution of all
the test methods in the suite.
@BeforeTest - The @BeforeTest annotated method will be executed before the
execution of all the test methods of available classes belonging to that folder.
25
@AfterTest - The @AfterTest annotated method will be executed after the execution
of all the test methods of available classes belonging to that folder.
@BeforeClass - The @BeforeClass annotated method will be executed before the
first method of the current class is invoked.
@AfterClass - The @AfterClass annotated method will be invoked after the
execution of all the test methods of the current class.
@BeforeMethod - The @BeforeMethod annotated method will be executed before
each test method will run.
@AfterMethod - The @AfterMethod annotated method will run after the execution of
each test method.
-----------------------------------------------------------------
package testingFramework;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
@BeforeSuite
public void beforesuite()
{
System.out.println("Before Suite");
}
@AfterSuite
public void aftersuite()
{
System.out.println("after Suite");
}
@BeforeTest
public void BeforeTest()
{
System.out.println("Before Test");
}
@AfterTest
public void AfterTest()
{
System.out.println("After Test");
}
26
@BeforeMethod
public void BeforeMethod()
{
System.out.println("Before Method");
}
@AfterMethod
public void AfterMethod()
{
System.out.println("After Method");
}
@BeforeClass
public void BeforeClass()
{
System.out.println("Before Class");
}
@AfterClass
public void AfterClass()
{
System.out.println("After class");
}
#savingfile
#Sat Oct 22 20:27:27 GMT-12:00 2022
password=test1234
browser=chrome
training=Selenium
place=brussels
url=www.google.com
username=anees
Exercise:
package testingFramework;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
27
prop.load(fis);
GIT :
https://git-scm.com/downloads - to downlaod and install
GitHub is a website and cloud-based service that helps developers/testerd store and
manage their code. As well as track and control changes to their code.
https://github.com/testadmin155/shinningteam.git
Commands:
1. GIT init :
The git init command is the first command that you will run on Git.
The git init command is used to create a new blank repository.
It is used to make an existing project as a Git project.
3. git status - this command is used to check what are files need to be commited
4. git add . - this will add all the files which all need to be commited
8. then need to add SSH key of teh user system in the GITHUB Repository to get the
access.
GIT :
GitHub is a website and cloud-based service that helps developers/testerd store and manage
their code. As well as track and control changes to their code.
Commands:
1. GIT init :
The git init command is the first command that you will run on Git.
The git init command is used to create a new blank repository.
It is used to make an existing project as a Git project.
3. git status - this command is used to check what are files need to be commited
29
4. git add . - this will add all the files which all need to be commited
8. then need to add SSH key of teh user system in the GITHUB Repository to get the access.
How to Pull the code given Repository to local system first time:
Maven:
Maven is a software Management tool. It will take care few things to manage project.
it acts as a build Management tool for java framework
Using Maven commands we can execute the script from Jenkins
Installation of Maven
Goto Google : Search for MAven download --> click on first link and download the zip
file for widows.
Download Maven - https://maven.apache.org/download.cgi
download file - apache-maven-3.8.6-bin.zip
goto Environment variables and Set the Path and set the MAVEN_HOME
open Path and add : E:\Testing Session\SeleniumTraining\Maveninstaller\apache-
maven-3.8.6-bin\apache-maven-3.8.6\bin
MAVEN_HOME : E:\Testing Session\SeleniumTraining\Maveninstaller\apache-
maven-3.8.6-bin\apache-maven-3.8.6
Add the maven surefire plugins to POM.xml to execute the testng.xml file using
command line -
https://maven.apache.org/surefire/maven-surefire-plugin/examples/testng.html
Maven Profiling:
We can create the groups in TestNg and call the specific profiles from Pom.xml
create multiple TestNG files(Sanity, Regression, Full) and create its corresponding
profiles in POM.xml
POX.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0"
31
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/
xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>MavenProject</groupId>
<artifactId>FirstScript</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>FirstScript</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<profiles>
<profile>
<id>Sanity</id>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testngSanity.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>
<profile>
<id>Regression</id>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testngRegression.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
32
</plugins>
</pluginManagement>
</build>
</profile>
<profile>
<id>Full</id>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M7</version>
<configuration>
<suiteXmlFiles>
<suiteXmlFile>testngFull.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</profile>
</profiles>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>3.141.59</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.8.8</version>
<scope>test</scope>
</dependency>
</dependencies>
</project>
--------------------------------------------------------------------------
33
TestNGSanity.xml:
TestNGRegression:
TestNGFull.xml:
<class name="MavenProject.FirstScript.CarLoan"/>
<class name="MavenProject.FirstScript.Homeloan"/>
</classes>
</test> <!-- Test -->
</suite> <!-- Suite -->
Tests:
CarLoan :
package MavenProject.FirstScript;
import org.testng.annotations.Test;
@Test(groups= {"Sanity"})
public void logintoBranchforCarLoan()
{
System.out.println("logintoBranchforCarLoan");
}
@Test
public void logintoAPPforCarLoan()
{
System.out.println("logintoAPPforCarLoan");
}
Homeloan :
package MavenProject.FirstScript;
import org.testng.annotations.Test;
@Test(groups= {"Sanity"})
public void logintoBranchforHomeLoan()
{
System.out.println("logintoBranchforHomeLoan");
}
@Test
public void logintoAPPforHomeLoan()
{
System.out.println("logintoAPPforHomeLoan");
35
PersonalLoan :
package MavenProject.FirstScript;
import org.testng.annotations.Test;
@Test(groups= {"Sanity"})
public void logintoBranchforPersonalLoan()
{
System.out.println("logintoBranchforCPersonalLoan");
}
@Test
public void logintoAPPforPersonalLoan()
{
System.out.println("logintoAPPforPersonalLoan");
}