0% found this document useful (0 votes)
55 views78 pages

What Is Software Testing?

The document provides information about software testing and Selenium. It defines software testing as identifying correctness and quality of software programs by checking if they satisfy customer requirements. It also describes manual vs automation testing. Automation testing involves writing scripts to test a product repeatedly. The document then discusses what Selenium is, how it supports different browsers, platforms and languages. It explains that Selenium includes IDE, RC, Grid and WebDriver and describes what each component is used for.

Uploaded by

pkgaming114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
55 views78 pages

What Is Software Testing?

The document provides information about software testing and Selenium. It defines software testing as identifying correctness and quality of software programs by checking if they satisfy customer requirements. It also describes manual vs automation testing. Automation testing involves writing scripts to test a product repeatedly. The document then discusses what Selenium is, how it supports different browsers, platforms and languages. It explains that Selenium includes IDE, RC, Grid and WebDriver and describes what each component is used for.

Uploaded by

pkgaming114
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Use Eclipse IDE for Java Developers Version: 2020-03 (4.15.

0) and for
that you have jdk higher version.

Software Testing
What is Software Testing?
• Software Testing is the process of identifying the correctness and quality of software programs. The purpose is
to check whether the software satisfies the specific requirements, needs, and expectations of the customer. In
other words, testing is executing a system or application in order to find software bugs, defects or errors. The
job of testing is to find out the reasons for application failures so that they can be corrected according to
requirements.
• Software testing can be stated as the process of verifying and validating that a software or application is
bug free, meets the technical requirements as guided by it’s design and development and meets the user
requirements effectively and efficiently with handling all the exceptional and boundary cases.
• The process of software testing aims not only at finding faults in the existing software but also at finding
measures to improve the software in terms of efficiency, accuracy and usability. It mainly aims at
measuring specification, functionality and performance of a software program or application.

Verification Validation
Verification addresses the concern: "Are you Validation addresses the concern: "Are you
building it right?" building the right thing?"

Ensures that the software system meets all the Ensures that the functionalities meet the intended
functionality. behavior.

Verification takes place first and includes the Validation occurs after verification and mainly
checking for documentation, code, etc. involves the checking of the overall product.

Done by developers. Done by testers.

It has static activities, as it includes collecting It has dynamic activities, as it includes executing
reviews, walkthroughs, and inspections to verify a the software against the requirements.
software.

It is an objective process and no subjective It is a subjective process and involves subjective


decision should be needed to verify a software. decisions on how well a software works.

Software Testing can be broadly classified into two types:

1. Manual Testing: Manual testing includes testing a software manually, i.e., without using any
automated tool or any script. In this type, the tester takes over the role of an end-user and
tests the software to identify any unexpected behavior or bug. There are different stages for
manual testing such as unit testing, integration testing, system testing, and user acceptance
testing
Testers use test plans, test cases, or test scenarios to test a software to ensure the
completeness of testing. Manual testing also includes exploratory testing, as testers explore
the software to identify errors in it.

Test Test Test Steps Test Data Expected Actual Pass/Fail


Case Scenario Results Results
ID

TU01 Check 1. Go to site http://www.facebook.com Userid = User should As Pass


Customer 2.Enter UserId a@yahoo.in Login into Expected
Login with 3.Enter Password Password = an
valid Data 4.Click Submit 1234 application

TU02 Check 1. Go to site http://www.facebook.com Userid = User should As Pass


Customer 2.Enter UserId a@yahoo.in not Login Expected
Login with 3.Enter Password Password = into an
invalid Data 4.Click Submit 4321 application
Project Name: Banking System

Test Case
Test Case ID: BU_001 Test Designed by: <Name>

Test Priority (Low/Medium/High): Med Test Designed date: <Date>

Module Name: Bank login screen Test Executed by: <Name>

Test Title: Test the Login Functionality in Banking Test Execution date: <Date>

Description: Verify login with valid username and


password

Pre-conditions: User has valid username and password

Dependencies:

Expected Status
Step Test Steps Test Data Actual Result Notes
Result (Pass/Fail)

Navigate to User should is


1 Pass
login page User should able to login
be able to
login

Credential
Provide valid
2 User= example@gmail.com can be As Expected Pass
username
entered

Credential
Provide valid
3 Password: 1234 can be As Expected Pass
password
entered
Click on Login User logged
4 User logged Pass
button successfully

2. Automation Testing: Automation testing, which is also known as Test Automation, is when
the tester writes scripts and uses another software to test the product. This process involves
automation of a manual process. Automation Testing is used to re-run the test scenarios that
were performed manually, quickly, and repeatedly.

Apart from regression testing, automation testing is also used to test the application from load,
performance, and stress point of view. It increases the test coverage, improves accuracy, and
saves time and money in comparison to manual testing.
What is Selenium
Selenium is one of the most widely used open source Web UI (User Interface) automation testing suite.It
was originally developed by Jason Huggins in 2004 as an internal tool at Thought Works. Selenium
supports automation across different browsers, platforms and programming languages.

Selenium can be easily deployed on platforms such as Windows, Linux, Solaris and Macintosh. Moreover, it
supports OS (Operating System) for mobile applications like iOS, windows mobile and android.

Selenium supports a variety of programming languages through the use of drivers specific to each
language.Languages supported by Selenium include C#, Java, Perl, PHP, Python and Ruby.Currently,
Selenium Web driver is most popular with Java and C#. Selenium test scripts can be coded in any of the
supported programming languages and can be run directly in most modern web browsers. Browsers
supported by Selenium include Internet Explorer, Mozilla Firefox, Google Chrome and Safari.

Selenium can be used to automate functional tests and can be integrated with automation test tools such
as Maven, Jenkins, & Docker to achieve continuous testing. It can also be integrated with tools such
as TestNG, & JUnit for managing test cases and generating reports.

Who developed Selenium?


Since Selenium is a collection of different tools, it had different developers as well. Below
are the key persons who made notable contributions to the Selenium Project

Primarily, Selenium was created by Jason Huggins in 2004. An engineer at


ThoughtWorks.

Multiple Languages Binding SUPPORT


Multiple Browsers SUPPORT

Multiple Platforms SUPPORT


Selenium Types
Selenium is not just a single tool but a suite of software, each catering to different testing needs of an
organization. It has four components:

• Selenium Integrated Development Environment (IDE)


• Selenium Remote Control (RC)
• Selenium Grid
• Selenium WebDriver

Selenium IDE

Selenium IDE (Integrated Development Environment) is a tool that helps you develop your Selenium
test cases. It’s an easy-to-use Chrome and Firefox extension and is generally the most reliable
method to develop test cases. It records users’ actions in the browser for you, using the existing
Selenium commands, with parameters defined by the context of the web element. This is not only a
time-saver but also an excellent way of learning Selenium script syntax. Previously known as
Selenium Recorder, Selenium IDE was initially created by Shinya Kasatani, of Japan and contributed
to the Selenium project in 2006.

It was introduced as a Firefox plugin for faster creation of test cases. As it was a Firefox extension, it
could automate the browser through a record-and-play feature providing autocompletion support and
the ability to move commands around quickly.

Scripts are recorded in a special test scripting language called Selenese for Selenium. Selenese
comes up with commands for carrying out actions in a web browser and restoring data from the
resulting pages.

The advantage of Selenium IDE is that the tests recorded via the plugin can be exported in different
programming languages like Java, Ruby, Python, etc.
Selenium RC (Remote Control)

Let me first tell you that Selenium Core was the first version. But with that version, testers had to
install both Selenium (a JavaScript program) and the webserver containing the web application being
tested on their local systems so that they would belong to the same domain.

Then, another ThoughtWorks’ engineer, Paul Hammant decided to create a server that will act as an
HTTP proxy to trick the browser into believing that Selenium Core and the web application being
tested belong to the same domain, thus making RC a two-component tool.

• Selenium RC Server
• Selenium RC Client (Library containing the programming language code)

RC can support the following programming languages:

• Java
• C#
• PHP
• Python
• Perl
• Ruby
Selenium Grid

Selenium Grid is a testing tool that lets you run your tests on various machines against different
browsers. It is part of the Selenium suite that specializes in running multiple tests across different
browsers, operating systems, and machines. You can connect to it with Selenium Remote Control by
stating the browser version, browser, and operating system as per your choice. You will be able to
specify these values through Selenium Remote Control capabilities. With Selenium Grid, one server
makes a move as a hub. Tests communicate to the hub to get access to browser instances. The hub
has a list of servers that provide access to browser instances (WebDriver nodes) and lets tests use
these instances.

Selenium Grid allows parallel testing and also allows managing different browser versions and
browser configurations centrally (instead of in each individual test).
There are multiple online platforms that provide an online Selenium Grid that you can access to run
your Selenium automation scripts. For example, you can use LambdaTest.

Selenium Grid has more than 2,000 browser environments over which you can run your tests and
truly automate cross-browser testing.
Selenium WebDriver

Founded by Simon Stewart in 2006, ThoughtWorks consultant in Australia. Selenium WebDriver was
the first cross-platform testing framework that would control the browser at the OS level. Selenium
WebDriver is a successor to Selenium RC. Selenium WebDriver accepts commands (sent in
Selenium or via a Client API) and sends them to a browser.

This is implemented through a browser-specific driver, which sends commands to a browser and
retrieves the results. Each driver launches and accesses a browser application. Different WebDrivers
are:

• Firefox Driver (Gecko Driver)


• Chrome Driver
• Internet Explorer Driver
• MicroEdge
• Opera Driver
• Safari Driver
• HTML Unit Driver

Configuration selenium with eclipse


• Java JDK Installation
• Eclipse Installation
• Install Selenium Driver Files
• Performing Selenium Test Case

Installing Java JDK

Step 1: Download Java JDK from the link provided below and then click on the Oracle
JDK Download button
https://www.oracle.com/technetwork/java/javase/downloads/index.html

Click on the radio button, Accept License Agreement, and download the .exe file related to your
OS type
Step 2: Open the downloaded execution file, and click on Next

Step 3: Select Developers Tools and click on Next, and you will be directed to the below screen.
It will take a few moments to set up JDK in your system
Step 4: Click on Close to complete the set up

Before moving ahead, you need to add the environment variables to the path as follows.

Step 5: Go to local C drive > Program Files > Java > jdk-12.0.1 > bin
Step 6: Copy the path as shown above
Step 7: Go to Control Panel > System and Security > System > Advanced system
settings > System Properties

Step 8: Click on Environment Variables as shown above and the below window pops up in
which you will perform the following steps:

1. Click on Path in the System variables section, under Environment Variables


2. Click on Edit
Step9:
1. Click on Browse and find your file path as local C drive > Program Files > Java > jdk-12.0.1
Keep clicking ‘OK’.
2. Now, you have Java JDK installed in your system
Installing Eclipse

Step 1: Go to the Eclipse download page (the recent one is Eclipse Installer 2019-06 R), with this
link: https://www.eclipse.org/downloads/
Step 2: Click on Download 64 bit. You would land on a page as shown below:

Step 3: Once the download is finished, launch the installer


Step 4: Click on Eclipse IDE for Enterprise Java Developers
Step 5: Once done, click on INSTALL
Step 6: Then, click on Launch
Install Selenium Driver Files

You can download the Selenium Java Client Driver


(https://www.selenium.dev/downloads/) here. You will find client drivers for other languages
there, but only choose the one for Java.

This download comes as a ZIP file named "selenium-3.14.0.zip". For simplicity, extract
the contents of this ZIP file on your C drive so that you would have the directory
"C:\selenium-3.14.0\". This directory contains all the JAR files that we would later
import on Eclipse.

Configure Eclipse IDE with WebDriver


1. Launch the "eclipse.exe" file inside the "eclipse" folder that we extracted in step 2. If
you followed step 2 correctly, the executable should be located on
C:\eclipse\eclipse.exe.
2. When asked to select for a workspace, just accept the default location.
3. Create a new project through File > New > Java Project. Name the project as
"newproject".

A new pop-up window will open enter details as follow

1. Project Name
2. Location to save project
3. Select an execution JRE
4. Select layout project option
5. Click on Finish button
4. In this step,

1. Right-click on the newly created project and


2. Select New > Package, and name that package as "newpackage".

A pop-up window will open to name the package,

1. Enter the name of the package


2. Click on Finish button

5. Create a new Java class under newpackage by right-clicking on it and then selecting-
New > Class, and then name it as "MyClass". Your Eclipse IDE should look like the image
below.
When you click on Class, a pop-up window will open, enter details as

1. Name of the class


2. Click on Finish button
This is how it looks like after creating class.

Now selenium WebDriver's into Java Build Path

In this step,

1. Right-click on "newproject" and select Properties.


2. On the Properties dialog, click on "Java Build Path".
3. Click on the Libraries tab, and then
4. Click on "Add External JARs.."

When you click on "Add External JARs.." It will open a pop-up window. Select the JAR
files you want to add.
After selecting jar files, click on OK button.

Select all files inside the lib folder.


Select files outside lib folder

Once done, click "Apply and Close" button


6. Add all the JAR files inside and outside the "libs" folder. Your Properties dialog should
now look similar to the image below.

6. Finally, click OK and we are done importing Selenium libraries into our project.
Different Drivers
A driver server is different for each browser. For example, Internet Explorer has its own
driver server which you cannot use on other browsers. Below is the list of driver servers
and the corresponding browsers that use them.

You can download these drivers here (http://seleniumhq.org/download/)

Chrome- https://sites.google.com/a/chromium.org/chromedriver/
Example-1
import org.openqa.selenium.WebDriver;
//import org.openqa.selenium.firefox.FirefoxDriver;
//comment the above line and uncomment below line to use Chrome
import org.openqa.selenium.chrome.ChromeDriver;
public class PG1 {

public static void main(String[] args) {


// declaration and instantiation of objects/variables
//System.setProperty("webdriver.gecko.driver","C:\\geckodriver.exe");
//WebDriver driver = new FirefoxDriver();
//comment the above 2 lines and uncomment below 2 lines to use Chrome
System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

String baseUrl = " http://bmusurat.ac.in/";


String expectedTitle = "Bhagwan Mahavir University BMEF";
String actualTitle = "";

// launch and direct it to the Base URL


driver.get(baseUrl);

// get the actual value of the title


actualTitle = driver.getTitle();

/*
* compare the actual title of the page with the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}

//close browser.
driver.close();

}
Explaining the code
Importing Packages
To get started, you need to import following two packages:

1. org.openqa.selenium.*- contains the WebDriver class needed to instantiate a new


browser loaded with a specific driver
2. org.openqa.selenium.chrome.ChromeDriver- contains the chromeDriver class
needed to instantiate a chrome-specific driver onto the browser instantiated by the
WebDriver class.

WebDriver Existence in package org.openqa.selenium


org.openqa.selenium: The global package of Selenium which we import in our
program every time when it is needed to use WebDriver. For reference, please see
“org.openqa.selenium” mind map below :-
• At a high level, if we can say that Driver means as per the selection of the Explorer
driver will be selected and Driver will be used to interact with Web Page.
• Web Page composed of Web Elements and these Drivers will communicate with the
Web Page.
• For communicating with Web Page means communication with Elements present on
the Web Page like for example: “Textboxes”, Buttons”, “Links” etc. “WebElement” a
sub interface of “SearchContext” comes into the picture. Let’s see this Interface also
(Methods name and description in the table below).

Instantiating objects and variables


Normally, this is how a driver object is instantiated.
WebDriver driver = new ChromeDriver();
A ChromeDriver class with no parameters means that the default Chrome profile will be
launched by our Java program. The default Chrome profile is similar to launching Chrome
in safe mode (no extensions are loaded).

For convenience, we saved the Base URL and the expected title as variables.

Launching a Browser Session


WebDriver's get() method is used to launch a new browser session and directs it to the
URL that you specify as its parameter.

Get the Actual Page Title


The WebDriver class has the getTitle() method that is always used to obtain the page title
of the currently loaded page.

Compare the Expected and Actual Values


This portion of the code simply uses a basic Java if-else structure to compare the actual
title with the expected one.

Terminating a Browser Session


The "close()" method is used to close the browser window.

Terminating the Entire Program


If you use this command without closing all browser windows first, your whole Java
program will end while leaving the browser window open.
we can generally classify Webdriver commands as:
• Browser commands,
• Get commands,
• Navigation commands,
• Webelement commands,
• Action commands and
• Result commands.

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

getCurrentUrl(): This method fetches the string representing the Current URL which is opened in
the browser. Accepts nothing as a parameter and returns a String value.
As the return type is String value, the output must be stored in String object/variable.
String CurrentUrl = driver.getCurrentUrl();

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

getPageSource(): This method returns the Source Code of the page. Accepts nothing as a parameter and
returns a String value.
As the return type is String value, the output must be stored in String object/variable.
String PageSource = driver.getPageSource();

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

quit(): This method Closes all windows opened by the WebDriver


driver.quit();
Note: Important to note that this command will only close the browser’s window opened by the
selenium in the same session. If any browser is opened manually, this will have no impact on
the same.

Navigate:-
How to Navigate to URL or How to open a webpage in Selenium Browser?
to(String arg0) : void – This method Loads a new web page in the current browser
window. It accepts a String parameter and returns nothing.

driver.navigate().to(appUrl);
example- driver.navigate().to("http://www.DemoQA.com");
It does exactly the same thing as the driver.get(appUrl) method. Where appUrl is
the website address to load. It is best to use a fully qualified URL.
Forward
How to browser Forward in Selenium Browser?
forward() : void – This method does the same operation as clicking on the Forward
Button of any browser. It neither accepts nor returns anything.
driver.navigate().forward();
example- driver.navigate().forward();
Takes you forward by one page on the browser’s history.

Back
How to browse backward in Selenium Browser?
back() : void – This method does the same operation as clicking on the Back
Button of any browser. It neither accepts nor returns anything.
driver.navigate().back();
example- driver.navigate().back ();
Takes youback by one page on the browser’s history.

Refresh
How to Refresh Selenium Browser?
refresh() : void – This method Refresh the current page. It neither accepts nor
returns anything.
driver.navigate().refresh();
Practice Exercise – 1
1. Launch a new Chrome browser.
2. Open bmefcolleges.edu.in
3. Get Page Title name and Title length
4. Print Page Title and Title length on the Eclipse Console.
5. Get Page URL and verify if it is a correct page opened
6. Get Page Source (HTML Source code) and Page Source length
7. Print Page Length on Eclipse Console.
8. Close the Browser.

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

public class Pro1 {

public static void main(String[] args) {

String driverExecutablePath = "D:\\Drivers\\chromedriver.exe";

System.setProperty("webdriver.chrome.driver", driverExecutablePath);

// Create a new instance of the Chrome driver

WebDriver driver = new ChromeDriver();

// Storing the Application Url in the String variable

String url = "http://bmefcolleges.edu.in ";

//Launch the ToolsQA WebSite

driver.get(url);

// Storing Title name in the String variable

String title = driver.getTitle();

// Storing Title length in the Int variable

int titleLength = driver.getTitle().length();

// Printing Title & Title length in the Console window

System.out.println("Title of the page is : " + title);

System.out.println("Length of the title is : "+ titleLength);

// Storing URL in String variable

String actualUrl = driver.getCurrentUrl();

if (actualUrl.equals(url)){

System.out.println("Verification Successful - The correct Url is opened.");

else {
System.out.println("Verification Failed - An incorrect Url is opened.");

//In case of Fail, you like to print the actual and expected URL for the record purpose

System.out.println("Actual URL is : " + actualUrl);

System.out.println("Expected URL is : " + url);

// Storing Page Source in String variable

String pageSource = driver.getPageSource();

// Storing Page Source length in Int variable

int pageSourceLength = pageSource.length();

// Printing length of the Page Source on console

System.out.println("Total length of the Pgae Source is : " + pageSourceLength);

//Closing browser

driver.close();

Practice Exercises for Selenium


Navigation Commands
1. Launch new Browser
2. Open DemoQA.com website
3. Click on Registration link using “driver.findElement(By.xpath(“.//*[@id=’menu-item-
374′]/a”)).click();“
4. Come back to Home page (Use ‘Back’ command)
5. Again go back to Registration page (This time use ‘Forward’ command)
6. Again come back to Home page (This time use ‘To’ command)
7. Refresh the Browser (Use ‘Refresh’ command)
8. Close the Browser
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class NavigateCommands {
public static void main(String[] args) {
// Create a new instance of the FireFox driver
WebDriver driver = new FirefoxDriver();

// Open ToolsQA web site


String appUrl = "http://www.DemoQA.com";
driver.get(appUrl);

// Click on Registration link


driver.findElement(By.xpath(".//*[@id='menu-item-374']/a")).click();

// Go back to Home Page


driver.navigate().back();

// Go forward to Registration page


driver.navigate().forward();

// Go back to Home page


driver.navigate().to(appUrl);

// Refresh browser
driver.navigate().refresh();

// Close browser
driver.close();
}
}
2.Selenium WebDriver Commands

• Browser Commands
• Navigation Commands
• WebElement Commands
• FindElement and FindElements Command
• CheckBox & Radio Button Operations
• DropDown & Multiple Select Operations
• Handle Dynamic WebTables in Selenium Webdriver

Browser Commands

The very basic browser operations of WebDriver include opening a browser; perform few tasks
and then closing the browser.

1. Get Command
Method:
get(String arg0) : void

this method loads a new web page in the existing browser window. It accepts String as
parameter and returns void.

String URL = "URL";


driver.get(URL);

Example:

driver.get("www.bmusurat.ac.in");

2. Get Title Command


Method:

getTitle(): String

this method fetches the title of the current web page. It accepts no parameter and returns a String.

Example:

String Title = driver.getTitle();

3. Get Current URL Command


Method:
getCurrentUrl(): String

this method fetches the string representing the Current URL of the current web page. It accepts nothing as parameter and returns a
String value.

Example:

String CurrentUrl = driver.getCurrentUrl();

4. Get Page Source Command


Method:
getPageSource(): String

this method returns the source code of the current web page loaded on the current browser. It accepts nothing as parameter and
returns a String value.
Example:

String PageSource = driver.getPageSource();

5. Close Command
Method:
close(): void

terminates the current browser window operating by WebDriver at the current time. If the current window is the only window
operating by WebDriver, it terminates the browser as well. This method accepts nothing as parameter and returns void.

Example:

driver.close();

6. Quit Command
Method:
quit(): void

terminates all windows operating by WebDriver. It terminates all tabs as well as the browser itself. It accepts nothing as parameter
and returns void.

Example:

driver.quit();

# this sample test, we will automate the following test scenarios:


Invoke Chrome Browser
Open URL: https://www.google.co.in/
Get Page Title name and Title length
Print Page Title and Title length on the Eclipse Console
Get page URL and verify whether it is the desired page or not
Get page Source and Page Source length
Print page Length on Eclipse Console.
Close the Browser.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class Web_command {

public static void main(String[] args) {

// System Property for Chrome Driver


System.setProperty("webdriver.chrome.driver","D:\\ChromeDriver\\chromedriver.exe");

// Instantiate a ChromeDriver class.


WebDriver driver=new ChromeDriver();

// Storing the Application Url in the String variable


String url = ("https://www.google.co.in/");

//Launch the ToolsQA WebSite


driver.get(url);

// Storing Title name in the String variable


String title = driver.getTitle();

// Storing Title length in the Int variable


int titleLength = driver.getTitle().length();

// Printing Title & Title length in the Console window


System.out.println("Title of the page is : " + title);
System.out.println("Length of the title is : "+ titleLength);

// Storing URL in String variable


String actualUrl = driver.getCurrentUrl();
if (actualUrl.equals("https://www.google.co.in/")){
System.out.println("Verification Successful - The correct Url is opened.");
}
else{
System.out.println("Verification Failed - An incorrect Url is opened.");
}

// Storing Page Source in String variable


String pageSource = driver.getPageSource();

// Storing Page Source length in Int variable


int pageSourceLength = pageSource.length();

// Printing length of the Page Source on console


System.out.println("Total length of the Pgae Source is : " + pageSourceLength);

//Closing browser
driver.close();

}
}

Navigation Commands
WebDriver provides some basic Browser Navigation Commands that allows the browser to move backwards or forwards in
the browser's history.

1. Navigate To Command
Method:
to(String arg0) : void

this method loads a new web page in the existing browser window. It accepts String as parameter and returns void.
driver.navigate().to("www.javatpoint.com");

Note: The get command (driver.get(URL);) which lies in the browser commands section does the same function as the navigate
command

2. Forward Command
Method:
to(String arg0) : void

this method enables the web browser to click on the forward button in the existing browser window. It neither accepts anything nor
returns anything.

driver.navigate().forward();

3. Back Command
Method:
back() : void

In WebDriver, this method enables the web browser to click on the back button in the existing browser window. It neither
accepts anything nor returns anything.

driver.navigate().back();

4. Refresh Command
Method:
refresh() : void

this method refresh/reloads the current web page in the existing browser window. It neither accepts anything nor returns anything.

The respective command that takes you back by one page on the browser's history can be written as:
driver.navigate().refresh();

# In this sample test, we will automate the following test scenarios:

Invoke Firefox Browser


Navigate to URL: https://www.testandquiz.com/selenium/testing.html
Click on the "This is a link" link (This link will redirect you to the javaTpoint website)
Come back to the Home page using the back command
Again go back to the javaTpoint website using forward command
Again come back to the Home page using To command
Refresh the Browser using Refresh command
Close the Browser.

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;

public class Navigation_command {

public static void main(String[] args) {

// System Property for Gecko Driver


System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );
// Initialize Gecko Driver using Desired Capabilities Class
DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette",true);
WebDriver driver= new FirefoxDriver(capabilities);

// Launch Website
driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");

//Click on the Link Text using click() command


driver.findElement(By.linkText("This is a Link")).click();

//Go back to Home Page


driver.navigate().back();

//Go forward to Registration page


driver.navigate().forward();

// Go back to Home page


driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");

//Refresh browser
driver.navigate().refresh();

//Closing browser
driver.close();
}
}

WebElement Commands

What is Web Element?


The term web element refers to a HTML element. The HTML documents are composed of HTML elements. It consists a start tag, an
end tag and the content in between. For instance, a HTML element is written as: "<tagname> content </tagname>" In WebDriver,
we have several commonly used web element commands and actions.
The following screenshot displays the eclipse web element command panel.
WebElement element = driver.findElement(By.id("UserName"));
Here, the UserName is the value of the id attribute, used as a unique identification for the desired web element.

1. Clear Command
Method:
clear() : void

Command:
element.clear();

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


element.clear();
//Or can be written as
driver.findElement(By.id("UserName")).clear();

2. Sendkeys Command
Method:
sendKeys(CharSequence? KeysToSend) : void

Command:
element.sendKeys("text");

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


element.sendKeys("JavaTpoint");
//Or can be written as
driver.findElement(By.id("UserName")).sendKeys("JavaTpoint");

3. Click Command
Method:
click() : void

Command:
element.click();

Code snippet:
WebElement element = driver.findElement(By.linkText("javaTpoint"));
element.click();
//Or can be written as
driver.findElement(By.linkText("javaTpoint")).click();

4. IsDisplayed Command
Method:
isDisplayed() : Boolean

Command:
element.isDisplayed();

Code snippet:

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


boolean status = element.isDisplayed();
//Or can be written as
boolean staus = driver.findElement(By.id("UserName")).isDisplayed();

5. IsEnabled Command
Method:
isEnabled() : Boolean

Command:
element.isEnabled();

Code snippet:
WebElement element = driver.findElement(By.id("UserName"));
boolean status = element.isEnabled();
//Or can be written as
boolean staus = driver.findElement(By.id("UserName")).isEnabled();
//Or can be used as
WebElement element = driver.findElement(By.id("userName"));
boolean status = element.isEnabled();
// Check that if the Text field is enabled, if yes enter value
if(status){
element.sendKeys("javaTpoint");
}

6. IsSelected Command
Method:
isSelected() : Boolean

Command:
element.isSelected();
Code snippet:

WebElement element = driver.findElement(By.id("Sex-Male"));


boolean status = element.isSelected();

//Or can be written as


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

7. Submit Command
Method:
submit() : void

Command:
element.submit();

Code snippet:
WebElement element = driver.findElement(By.id("SubmitButton"));
element.submit();
//Or can be written as
driver.findElement(By.id("SubmitButton")).submit();

8. GetText Command
Method:
getText() : String

Command:
element.getText();

Code snippet:
WebElement element = driver.findElement(By.xpath("anyLink"));
String linkText = element.getText();

9. GetTagName Command
Method:
getTagName() : String

Command:
element.getTagName();
Code snippet:

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


String tagName = element.getTagName();
//Or can be written as
String tagName = driver.findElement(By.id("SubmitButton")).getTagName();

10. getCssValue Command


Method:
getCssvalue() : String

Command:
element.getCssValue();

11. getAttribute Command


Method:
getAttribute(String Name) : String
Command:
element.getAttribute();

Code snippet:
WebElement element = driver.findElement(By.id("SubmitButton"));
String attValue = element.getAttribute("id"); //This will return "SubmitButton"

12. getSize Command


Method:
getSize() : Dimension

Command:
element.getSize();

Code snippet:
WebElement element = driver.findElement(By.id("SubmitButton"));
Dimension dimensions = element.getSize();
System.out.println("Height :" + dimensions.height + "Width : "+ dimensions.width);

13. getLocation Command


Method:
getLocation() : Point

Command:
element.getLocation();

Code snippet:
WebElement element = driver.findElement(By.id("SubmitButton"));
Point point = element.getLocation();
System.out.println("X cordinate : " + point.x + "Y cordinate: " + point.y);

FindElement and FindElements Command

findElement() – finds a single web element and returns as a WebElement object.


findElements() – returns a list of WebElement objects matching the locator criteria.

Locators
The method findElement() takes one parameter which is a locator to the element. Different
locators like By.id(), By.name(), By.xpath(), By.CSSSelector() etc. locate the elements in the page
using their properties like`````` id, name or path, etc.

Using the example site http://demo.guru99.com/test/login.html

locate the "Emailaddress" text field using the id locator and the "Password "field using the name
locator.
1. Email text field is located by Id
2. Password field is located by name

Entering Values in Input Boxes


To enter text into the Text Fields and Password Fields, sendKeys() is the method available on
the WebElement.

1. Find the "Email Address" Text field using the id locator.


2. Find the "Password" field using the name locator
3. Enter text into the "Email Address" using the sendKeys() method.
4. Enter a password into the "Password" field using the sendKeys() method.
Deleting Values in Input Boxes
The clear() method is used to delete the text in an input box. This method does not need a
parameter. The code snippet below will clear out the text from the Email or Password fields

Buttons
The buttons can be accessed using the click() method

In the example above


1. Find the button to Sign in
2. Click on the "Sign-in" Button in the login page of the site to login to the site.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.*;

public class Form {

public static void main(String[] args) {

// declaration and instantiation of objects/variables


System.setProperty("webdriver.chrome.driver","G:\\chromedriver.exe");
WebDriver driver = new ChromeDriver();

String baseUrl = "http://demo.guru99.com/test/login.html";


driver.get(baseUrl);

// Get the WebElement corresponding to the Email Address(TextField)


WebElement email = driver.findElement(By.id("email"));

// Get the WebElement corresponding to the Password Field


WebElement password = driver.findElement(By.name("passwd"));
email.sendKeys("abcd@gmail.com (mailto:abcd@gmail.com)");
password.sendKeys("abcdefghlkjl");
System.out.println("Text Field Set");

// Deleting values in the text box


email.clear();
password.clear();
System.out.println("Text Field Cleared");

// Find the submit button


WebElement login = driver.findElement(By.id("SubmitLogin"));
// Using click method to submit form
email.sendKeys("abcd@gmail.com (mailto:abcd@gmail.com)");
password.sendKeys("abcdefghlkjl");
login.click();

System.out.println("Login Done with Click");


//using submit method to submit the form. Submit used on password field
driver.get(baseUrl);
driver.findElement(By.id("email")).sendKeys("abcd@gmail.com (mailto:a
bcd@gmail.com)");
driver.findElement(By.name("passwd")).sendKeys("abcdefghlkjl");
driver.findElement(By.id("SubmitLogin")).submit();
System.out.println("Login Done with Submit");
//driver.close();
}
}
1. Fetching a web page
There are two methods to fetch a web page:
Using Get method

driver.get("www.javatpoint.com")

Using Navigate method


driver.navigate().to("https://javatpoint.com/selenium-tutorial");

2. Locating forms and sending user inputs


driver.findElement(By.id("lst-ib")).sendKeys("javatpoint tutorials");

3. Clearing User inputs


The clear() method is used to clear the user inputs from the text box.
driver.findElement(By.name("q")).clear();

4. Fetching data over any web element


Sometimes we need to fetch the text written over a web element for performing some assertions and debugging. We use getText()
method to fetch data written over any web element.
driver.findElement(By.id("element567")).getText();

5. Performing Click event


The click() method is used to perform click operation on any web element.
driver.findElement(By.id("btnK")).click();

6. Navigating backward in browser history


driver.navigate().back();

7. Navigating forward in browser history


driver.navigate().forward();

8. Refresh/ Reload a web page


driver.navigate().refresh();

9. Closing Browser
driver.close();

10. Closing Browser and other all other windows associated with the driver
driver.quit();

11. Moving between Windows


driver.switchTo().window("windowName");

13. Moving between Frames


driver.switchTo().frame("frameName");

14. Drag and Drop


Drag and Drop operation is performed using the Action class.
WebElement element = driver.findElement(By.name("source"));
WebElement target = driver.findElement(By.name("target"));

(new Actions(driver)).dragAndDrop(element, target).perform();


import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;

public class Second {

public static void main(String[] args) {


// System Property for Gecko Driver
System.setProperty("webdriver.gecko.driver","D:\\GeckoDriver\\geckodriver.exe" );

// Initialize Gecko Driver using Desired Capabilities Class


DesiredCapabilities capabilities = DesiredCapabilities.firefox();
capabilities.setCapability("marionette",true);
WebDriver driver= new FirefoxDriver(capabilities);

// Launch Website
driver.navigate().to("https://www.testandquiz.com/selenium/testing.html");
// Fetch the text "This is sample text." and print it on console

// Use the class name of the div to locate it and then fetch text using getText() method
String sampleText = driver.findElement(By.className("col-md-12")).getText();
System.out.println(sampleText);

// Use the linkText locator method to find the link and perform click using click() method
driver.findElement(By.linkText("This is a link")).click();

// Click on the textbox and send value


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

// Clear the text written in the textbox


driver.findElement(By.id("fname")).clear();

// Click on the Submit button using click() command


driver.findElement(By.id("idOfButton")).click();

// Locate the radio button by id and check it using click() function


driver.findElement(By.id("male")).click();

// Locate the checkbox by cssSelector and check it using click() function


driver.findElement(By.cssSelector("input.Automation")).click();

// Use Select class for selecting value from dropdown


Select dropdown = new Select(driver.findElement(By.id("testingDropdown")));
dropdown.selectByVisibleText("Automation Testing");

// Close the Browser


driver.close();
}
}
DropDown & Multiple Select Operations

import the package org.openqa.selenium.support.ui.Select

Step 1

Import the "Select" package.

Step 2

Declare the drop-down element as an instance of the Select class. In the example below,
we named this instance as "drpCountry".

Step 3

We can now start controlling "drpCountry" by using any of the available Select methods.
The sample code below will select the option "ANTARCTICA."
Selecting Items in a Multiple SELECT elements
We can also use the selectByVisibleText() method in selecting multiple options in a multi
SELECT element. As an example, we will take http://jsbin.com/osebed/2 as the base URL.
It contains a drop-down box that allows multiple selections at a time.

The code below will select the first two options using the selectByVisibleText() method.
Select Class in Selenium
Models a SELECT tag, providing helper methods to select and deselect options. Select is a class that
is provided by Selenium to perform multiple operations on DropDown object and Multiple Select
objects. This class can be found under the Selenium’s Support.UI.Select package. As Select is also
an ordinary class, so it’s object is also created by a New keyword with regular class creation syntax.
Select oSelect = new Select());

The above code will generate compile-time error in Eclipse, as Select() is asking for constructor. Bring the
cursor over Select(), Eclipse will populate a suggestion.

It clearly says that Select is asking for an element type object for its constructor. The code will be:

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


Select oSelect = new Select(element);

//Or it can be also written as

Select oSelect = new Select(driver.findElement(By.id("Country")));

selectByVisibleText
selectByVisibleText(String arg0) : void – It is very easy to choose or select an option given under
any dropdowns and multiple selection boxes with selectByVisibleText method. It takes a parameter of
String which is one of the Value of Select element and it returns nothing.
Command – oSelect.selectByVisibleText(“text”);
Example – Refer the above Screen shot of YEAR Drop Down*
Code – To select the value 2010.
Select oSelect = new Select(driver.findElement(By.id("yy_date_8")));

oSelect.selectByVisibleText("2010");

selectByIndex
selectByIndex(int arg0) : void – It is almost the same as selectByVisibleText but the only difference
here is that we provide the index number of the option here rather the option text. It takes a
parameter of int which is the index value of Select element and it returns nothing.
Command – oSelect.selectByIndex(int);
Example – Refer the above Screen shot of YEAR Drop Down*
Code – To select the value 2010 using index.

Select oSelect = new Select(driver.findElement(By.id("yy_date_8")));

oSelect.selectByIndex(4);
selectByValue
selectByValue(String arg0) : void –It is again the same as what we have discussed earlier, the only
difference in this is that it asks for the value of the option rather than the option text or index. It takes
a parameter of String which is on of the value of Select element and it returns nothing.
Command – oSelect.selectByValue(“text”);
Example – Refer the above Screen shot of YEAR Drop Down*
Code – To select the value 2014.

Select oSelect = new Select(driver.findElement(By.id("yy_date_8")));

oSelect.selectByValue("2014");

getOptions
getOptions( ) : List<WebElement> –This gets the all options belonging to the Select tag. It takes no
parameter and returns List<WebElements>.
Command – oSelect.getOptions();
Sometimes you may like to count the element in the dropdown and multiple select box, so that you
can use the loop on Select element.
Example – Refer the above Screen shot of YEAR Drop Down*
Code – To get the Count of the total elements inside SELECT.

Select oSelect = new Select(driver.findElement(By.id("yy_date_8")));


List <WebElement> elementCount = oSelect.getOptions();
System.out.println(elementCount.size());

Print all the Options


Code – To get the Count of the total elements inside SELECT and to Print the text value of every
element present in the SELECT.

Select oSelect = new Select(driver.findElement(By.id("yy_date_8")));


List <WebElement> elementCount = oSelect.getOptions();
int iSize = elementCount.size();

for(int i =0; i<iSize ; i++){


String sValue = elementCount.get(i).getText();
System.out.println(sValue);
}

DeSelect Methods
The way we select different values of DropDown & Multi Select, the same way we can
also deselect the values. But the only challenge in these methods are they do not work
for DropDown and only work for Multi Select elements.
In case you want to deselect any pre-selected option, that can be done with either deselectAll(),
deselectByIndex, deselectByValue and deselectByVisibletext.

deselectAll( ) : void – Clear all selected entries. This is only valid when the SELECT supports
multiple selections.
Command – oSelect.deselectAll;
deselectByIndex(int arg0) : void –Deselect the option at the given index.
Command – oSelect.deselectByIndex;
deselectByValue(String arg0) : void –Deselect all options that have a value matching the
argument.
Command – oSelect.deselectByValue;
deselectByVisibleText(String arg0) : void – Deselect all options that display text matching the
argument.
Command – oSelect.deselectByVisibleText

isMultiple
isMultiple( ) : boolean – This tells whether the SELECT element support multiple selecting options
at the same time or not. This accepts nothing but returns boolean value(true/false).
Command – oSelect.isMultiple();
This is done by checking the value of the “multiple” attribute.
Example – Refer the above Screen shot of MULTI SELECT for multiple attribute*

Multi Select Methods


This one also just works on Multiple selection boxes and not on regular List boxes or dropdowns.
There is no additional logic behind selecting multiple options of Select element. All you need to do is
to fire select commands on multiple elements one by one that’s it.

Select oSelect = new Select(driver.findElement(By.id(Element_ID)));


oSelect.selectByIndex(index)
oSelect.selectByIndex(index)

// Or can be used as

oSelect.selectByVisibleText(text)
oSelect.selectByVisibleText(text)

// Or can be used as

oSelect.selectByValue(value)
oSelect.selectByValue(value)
Practice Exercise -1 (Drop Down Box/List)
1. Launch new Browser
2. Open “http://toolsqa.com/automation-practice-form/”
3. Select ‘Continents’ Drop down ( Use Id to identify the element )
4. Select option ‘Europe’ (Use selectByIndex)
5. Select option ‘Africa’ now (Use selectByVisibleText)
6. Print all the options for the selected drop down and select one option of your choice
7. Close the browser

package automationFramework;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class DropDownCommands {
public static void main(String[] args) throws InterruptedException {
// Create a new instance of the FireFox driver
WebDriver driver = new FirefoxDriver();

// Put an Implicit wait,


driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch the URL


driver.get("http://toolsqa.com/automation-practice-form");

// Step 3: Select 'Continents' Drop down ( Use Id to identify the


element )
// Find Select element of "Single selection" using ID locator.
Select oSelect = new
Select(driver.findElement(By.id("continents")));

// Step 4:) Select option 'Europe' (Use selectByIndex)


oSelect.selectByVisibleText("Europe");

// Using sleep command so that changes can be noticed


Thread.sleep(2000);

// Step 5: Select option 'Africa' now (Use selectByVisibleText)


oSelect.selectByIndex(2);
Thread.sleep(2000);

// Step 6: Print all the options for the selected drop down and select
one option of your choice
// Get the size of the Select element
List<WebElement> oSize = oSelect.getOptions();
int iListSize = oSize.size();

// Setting up the loop to print all the options


for(int i =0; i < iListSize ; i++){
// Storing the value of the option
String sValue = oSelect.getOptions().get(i).getText();
// Printing the stored value
System.out.println(sValue);
// Putting a check on each option that if any of the option is
equal to 'Africa" then select it
if(sValue.equals("Africa")){
oSelect.selectByIndex(i);
break;
}
}
// Kill the browser
driver.quit();
}
}

Practice Exercise -2 (Multiple Selection Box/List)


1. Launch new Browser
2. Open “http://toolsqa.com/automation-practice-form/”
3. Select ‘Selenium Commands’ Multiple selection box ( Use Name locator to identify the element )
4. Select option ‘Browser Commands’ and then deselect it (Use selectByIndex and deselectByIndex)
5. Select option ‘Navigation Commands’ and then deselect it (Use selectByVisibleText and
deselectByVisibleText)
6. Print and select all the options for the selected Multiple selection list.
7. Deselect all options
8. Close the browser

package automationFramework;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;

public class MultiSelectCommands {

public static void main(String[] args) throws InterruptedException {


// Create a new instance of the FireFox driver
WebDriver driver = new FirefoxDriver();
// Put an Implicit wait
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

// Launch the URL


driver.get("http://toolsqa.com/automation-practice-form");

// Step 3: Select 'Selenium Commands' Multiple select box ( Use


Name locator to identify the element )
Select oSelect = new
Select(driver.findElement(By.name("selenium_commands")));

// Step 4: Select option 'Browser Commands' and then deselect it


(Use selectByIndex and deselectByIndex)
oSelect.selectByIndex(0);
Thread.sleep(2000);
oSelect.deselectByIndex(0);

// Step 5: Select option 'Navigation Commands' and then deselect it


(Use selectByVisibleText and deselectByVisibleText)
oSelect.selectByVisibleText("Navigation Commands");
Thread.sleep(2000);
oSelect.deselectByVisibleText("Navigation Commands");

// Step 6: Print and select all the options for the selected Multiple
selection list.
List<WebElement> oSize = oSelect.getOptions();
int iListSize = oSize.size();

// Setting up the loop to print all the options


for(int i =0; i < iListSize ; i++){
// Storing the value of the option
String sValue = oSelect.getOptions().get(i).getText();

// Printing the stored value


System.out.println(sValue);

// Selecting all the elements one by one


oSelect.selectByIndex(i);
Thread.sleep(2000);
}

// Step 7: Deselect all


oSelect.deselectAll();

// Kill the browser


driver.close();
}
}
Handle Dynamic WebTables in Selenium Webdriver

There are two types of HTML tables published on the web-

1. Static tables: Data is static i.e. Number of rows and columns are fixed.
2. Dynamic tables: Data is dynamic i.e. Number of rows and columns are NOT fixed.

There are two types of HTML tables published on the web-

1. Static tables: Data is static i.e. Number of rows and columns are fixed.
2. Dynamic tables: Data is dynamic i.e. Number of rows and columns are NOT fixed.

Below is an example of a dynamic table of Sales. Based on input date filters, number of
rows will get altered. So, it is dynamic in nature.

Using X-Path to Locate Web Table Elements


Before we locate web element, first let's understands-

What is a web element?

Web elements are nothing but HTML elements like textbox, dropdowns radio buttons,
submit buttons, etc. These HTML elements are written with start tag and ends with
an end tag.
For Example,

<p> My First HTML Document</p>.

Steps for getting X-path of web element that we want to locate.

Step 1) In Chrome, Go to http://demo.guru99.com/test/web-table-element.php

Step 2) Right click on web element whose x-path is to be fetched. In our case, right click
on "Company" Select Inspect option. The following screen will be shown -
Step 3) Right Click on highlighted web element > Select Copy -> Copy x-path option.
Step 4) Use the copied X-path "//*[@id="leftcontainer"]/table/thead/tr/th [1]" in Selenium
WebDriver to locate the element.

Example: Fetch number of rows and columns from


Dynamic WebTable
When the table is dynamic in nature, we cannot predict its number of rows and columns.

Using Selenium web driver, we can find

• Number of Rows and columns of web table


• X row or Y column's data.

import java.text.ParseException;
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;

public class Noofrowsandcols {


public static void main(String[] args) throws ParseException {
WebDriver wd;
System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
wd= new ChromeDriver();
wd.get("http://demo.guru99.com/test/web-table-element.php");
//No.of Columns
List col = wd.findElements(By.xpath(".//*[@id=\"leftcontainer\"]/table/thead/tr/th"));
System.out.println("No of cols are : " +col.size());
//No.of rows
List rows = wd.findElements(By.xpath(".//*[@id='leftcontainer']/table/tbody/tr/td[1]"));
System.out.println("No of rows are : " + rows.size());
wd.close();
}
}

Code Explanation:

• Here we have first declared Web Driver object "wd" &initialized it to chrome driver.
• We use List <WebElement> to total number of columns in "col".
• findElements commands returns a list of ALL the elements matching the specified
locator
• using findElements and X-path //*[@id=\"leftcontainer\"]/table/thead/tr/th we get all
the columns
• Similarly, we repeat the process for rows.

Example: Fetch cell value of a particular row and column


of the Dynamic Table
Let's assume we need 3rd row of the table and its second cell's data. See the table below-
In above table, data is regularly updated after some span of time. The data you try retrieve
will be different from the above screenshot. However, the code remains the same. Here is
sample program to get the 3rd row and 2nd column's data.
import java.text.ParseException;
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;
import java.util.concurrent.TimeUnit;

public class RowandCell {


public static void main(String[] args) throws ParseException {
WebDriver wd;
System.setProperty("webdriver.chrome.driver","G://chromedriver.exe");
wd= new ChromeDriver();
wd.get("http://demo.guru99.com/test/web-table-element.php");
wd.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
WebElement baseTable = wd.findElement(By.tagName("table"));

//To find third row of table


WebElement tableRow = baseTable.findElement(By.xpath("//*[@id=\"leftcontainer\"]
/table/tbody/tr[3]"));
String rowtext = tableRow.getText();
System.out.println("Third row of table : "+rowtext);

//to get 3rd row's 2nd column data


WebElement cellIneed = tableRow.findElement(By.xpath("//*[@id=\"leftcontainer
\"]/table/tbody/tr[3]/td[2]"));
String valueIneed = cellIneed.getText();
System.out.println("Cell value is : " + valueIneed);
wd.close();
}
}

Code Explanation:

• Table is located using locator property "tagname".


• Using XPath "//*[@id=\"leftcontainer\"]/table/tbody/tr[3]" find the 3rd row and gets its
text using getText () function
• Using Xpath "//*[@id=\"leftcontainer\"]/table/tbody/tr[3]/td[2]" find the 2nd cell in
3rd row and gets its text using getText () function

Output:

additional example:

https://www.guru99.com/handling-dynamic-selenium-webdriver.html

3 Navigate back/forwards, get, refresh


I_ loading a page in current window / New window
2. Move back and forward
3. Refresh Page

1. driver.navigate().forward(); – to navigate to the next web page with reference to the


browser’s history
2. driver.navigate().back(); – takes back to the previous web page with reference to the
browser’s history
3. driver.navigate().refresh(); – to refresh the current web page thereby reloading all
the web elements
4. driver.navigate().to(“url”); – to launch a new web browser window and navigate to
the specified URL

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Navigation_Commands {

public static void main(String[] args)throws


InterruptedException{

// Set geckodriver path


System.setProperty("webdriver.gecko.driver","D:\\geckodriver.exe");

// Instantiating objects and variables


WebDriver driver = new FirefoxDriver();

// Wait For Page To Load


driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

// Using navigate to command navigate to another url


driver.navigate().to("https://stqatools.com/");

// Using Back command navigate to back page


driver.navigate().back();

// Using Forward command navigate to forward page


driver.navigate().forward();

// Using Refresh command Refresh current page


driver.navigate().refresh();
}
}
4 Interrogation:
i) get window title
ii) current url
iii) Page source

# importing webdriver from selenium

from selenium import webdriver

# Here Chrome will be used

driver = webdriver.Chrome()

# URL of website

url = "https://www.google.com/"

# Getting current URL source code

get_title = driver.title

# Printing the title of this URL

# Here it is null string

print(get_title, " ", len(get_title))

# Opening the website

driver.get(url)

# Getting current URL source code

get_title = driver.title

# Printing the title of this URL

print(get_title, " ", len(get_title))

String actualUrl = driver.getCurrentUrl();


if (actualUrl.equals(url)){

System.out.println("Verification Successful - The correct Url is opened.");

else {

System.out.println("Verification Failed - An incorrect Url is opened.");

/ Storing Page Source in String variable


String pageSource = driver.getPageSource();

// Storing Page Source length in Int variable


int pageSourceLength = pageSource.length();

// Printing length of the Page Source on console


System.out.println("Total length of the Pgae Source is : " + pageSourceLength);

Locating web elements by Id, ClassName,LinkText,PartialLinkText,Name,TagName,


CssSelector , XPath

4.1. Locating by Id
<html>

<body>

<form id="loginForm">

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

<input name="password" type="password" />

<input name="continue" type="submit" value="Login" />

</form>

</body>

<html>

The form element can be located like this:

login_form = driver.find_element_by_id('loginForm')
4.2. Locating by Name
<html>

<body>

<form id="loginForm">

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

<input name="password" type="password" />

<input name="continue" type="submit" value="Login" />

<input name="continue" type="button" value="Clear" />

</form>

</body>

<html>

The username & password elements can be located like this:

username = driver.find_element_by_name('username')

password = driver.find_element_by_name('password')

4.3. Locating by XPath


<body>

<form id="loginForm">

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

<input name="password" type="password" />

<input name="continue" type="submit" value="Login" />

<input name="continue" type="button" value="Clear" />

</form>

</body>

<html>

The form elements can be located like this:


login_form = driver.find_element_by_xpath("/html/body/form[1]")

login_form = driver.find_element_by_xpath("//form[1]")

login_form = driver.find_element_by_xpath("//form[@id='loginForm']")

1. Absolute path (would break if the HTML was changed only slightly)
2. First form element in the HTML
3. The form element with attribute named id and the value loginForm

username = driver.find_element_by_xpath("//form[input/@name='username']")

username = driver.find_element_by_xpath("//form[@id='loginForm']/input[1]")

username = driver.find_element_by_xpath("//input[@name='username']")

1. First form element with an input child element with attribute named name and the
value username
2. First input child element of the form element with attribute named id and the
value loginForm
3. First input element with attribute named ‘name’ and the value username

clear_button = driver.find_element_by_xpath("//input[@name='continue'][@type='button']")

clear_button = driver.find_element_by_xpath("//form[@id='loginForm']/input[4]")

1. Input with attribute named name and the value continue and attribute named type and
the value button
2. Fourth input child element of the form element with attribute named id and
value loginForm

4.4. Locating Hyperlinks by Link Text


<html>

<body>

<p>Are you sure you want to do this?</p>

<a href="continue.html">Continue</a>
<a href="cancel.html">Cancel</a>

</body>

<html>

The continue.html link can be located like this:

continue_link = driver.find_element_by_link_text('Continue')

continue_link = driver.find_element_by_partial_link_text('Conti')

4.5. Locating Elements by Tag Name


<html>

<body>

<h1>Welcome</h1>

<p>Site content goes here.</p>

</body>

<html>

The heading (h1) element can be located like this:

heading1 = driver.find_element_by_tag_name('h1')

4.6. Locating Elements by Class Name


For instance, consider this page source:

<html>

<body>

<p class="content">Site content goes here.</p>

</body>

<html>

The “p” element can be located like this:

content = driver.find_element_by_class_name('content')
4.7. Locating Elements by CSS Selectors
<html>

<body>

<p class="content">Site content goes here.</p>

</body>

<html>

The “p” element can be located like this:

content = driver.find_element_by_css_selector('p.content')
Inspecting elements in web browsers

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy