0% found this document useful (0 votes)
9 views44 pages

Selenium Code

The document contains multiple Java classes that utilize Selenium WebDriver for web automation tasks, including testing page titles, login functionalities, registration processes, and product detail navigation on various web pages. It demonstrates how to interact with web elements using different locating strategies such as ID, XPath, and CSS selectors. Additionally, it includes examples of handling dropdowns, form submissions, and verifying navigation success through URL checks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views44 pages

Selenium Code

The document contains multiple Java classes that utilize Selenium WebDriver for web automation tasks, including testing page titles, login functionalities, registration processes, and product detail navigation on various web pages. It demonstrates how to interact with web elements using different locating strategies such as ID, XPath, and CSS selectors. Additionally, it includes examples of handling dropdowns, form submissions, and verifying navigation success through URL checks.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

#1

import [Link];
import [Link];

public class FlipkartTitleTest{


public static void main(String[] args){
[Link]("[Link]",
"PATH_TO_CHROMEDRIVER");
WebDriver driver = new ChromeDriver();
[Link]("[Link]
String title = [Link]();
[Link](title);
[Link]();

}
}

#2
import [Link];
import [Link];
import [Link];
import [Link];

public class LoginTest{


public static void main(String[] args){

// Set the path to the ChromeDriver executable


[Link]("[Link]",
"PATH_TO_CHROMEDRIVER");

// Launch the Chrome Browser


WebDriver driver = new ChromeDriver();

// Navigate to the login page


[Link]("[Link]

// Find the username input element


WebElement usernameEl =
[Link]([Link]("username"));
// Enter the username
[Link]("rahul");

}
}

#3

WebElement element =
[Link]([Link]("locator"));
WebElement usernameEl =
[Link]([Link]("username"));

#4

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class RegistrationTest{


public static void main(String[] args){

// Set the path to the ChromeDriver executable


[Link]("[Link]",
"PATH_TO_CHROMEDRIVER");

// Launch the Chrome Browser


WebDriver driver = new ChromeDriver();

// Open the NxtTrendz registration page


[Link]("[Link]

// Find the username input element


WebElement nameField =
[Link]([Link]("name"));
[Link]("rahul");

// Find the email input element


WebElement emailField =
[Link]([Link]("email"));
[Link]("rahul@[Link]");
// Find the password input element
WebElement passwordField =
[Link]([Link]("password"));
[Link]("rahul@2021");

// Find the male radio button


WebElement genderField =
[Link]([Link]("male"));
[Link]();

// Find the country dropdown element


WebElement countryDropdown =
[Link]([Link]("country"));
Select countrySelect = new Select(countryDropdown);
// Select an option by visible text
[Link]("India");
}
}

#5

// Select element = new Select(webElement);


<select id="dropdownId">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>

WebElement dropdown =
[Link]([Link]("dropdownId"));

// Create a Select object


Select select = new Select(dropdown);
[Link]("Option 1");

WebElement dropdown =
[Link]([Link]("dropdownId"));

// Create a Select object


Select select = new Select(dropdown);
[Link]("2");

WebElement dropdown =
[Link]([Link]("dropdownId"));

// Create a Select object


Select select = new Select(dropdown);
[Link](2);

#6
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class RegistrationTest{


public static void main(String[] args){

// Set the path to the ChromeDriver executable


[Link]("[Link]",
"PATH_TO_CHROMEDRIVER");

// Launch the Chrome Browser


WebDriver driver = new ChromeDriver();

// Open the NxtTrendz registration page


[Link]("[Link]

// Find the username input element


WebElement nameField =
[Link]([Link]("name"));
[Link]("rahul");

// Find the email input element


WebElement emailField =
[Link]([Link]("email"));
[Link]("rahul@[Link]");
// Find the password input element
WebElement passwordField =
[Link]([Link]("password"));
[Link]("rahul@2021");

// Find the male radio button


WebElement genderField =
[Link]([Link]("male"));
[Link]();

// Find the country dropdown element


WebElement countryDropdown =
[Link]([Link]("country"));
Select countrySelect = new Select(countryDropdown);

// Select an option by visible text


[Link]("India");

// Select the checkbox


WebElement termsAndConditions =
[Link]([Link]("terms"));
[Link]();

// Submit the registration form


WebElement registerButton =
[Link]([Link]("submitBtn") );
[Link]();

// Navigate to Login Page


WebElement loginPageEl =
[Link]([Link]("Log"));
[Link]();
// Define the expected URL
String loginPageUrl =
"[Link]

// Get the current URL


String currentUrl = [Link]();

// Verify the successful navigation

if([Link](loginPageUrl)){
[Link]("Navigated to Login Page");
}else{
[Link]("Failed to open Login Page");
}

}
}

#7 X path
import [Link];
import [Link];
import [Link];
import [Link];

public class LoginTest {


public static void main(String[] args) {

// Set the path to the ChromeDriver executable


[Link]("[Link]",
"PATH_TO_CHROMEDRIVER");

// Launch the Chrome Browser


WebDriver driver = new ChromeDriver();

// Open the NxtTrendz login page


[Link]("[Link]
WebElement usernameEl =
[Link]([Link]("/html/body/div[1]/div/form/
div[1]/input"));
[Link]("rahul");

}
}

##8
Xpaths test

import [Link];
import [Link];
import [Link];
import [Link];

public class LoginTest {


public static void main(String[] args) {

// Set the path to the ChromeDriver executable


[Link]("[Link]",
"PATH_TO_CHROMEDRIVER");

// Launch the Chrome Browser


WebDriver driver = new ChromeDriver();

// Open the NxtTrendz login page


[Link]("[Link]

// Enter the username


WebElement usernameEl =
[Link]([Link]("/html/body/div[1]/div/form/
div[1]/input"));
[Link]("rahul");

// Enter the password


WebElement passwordEl =
[Link]([Link]("/html/body/div[1]/div/form/
div[2]/input"));
[Link]("rahul@2021");
// Submit the login details
WebElement buttonEl =
[Link]([Link]("/html/body/div[1]/div/form/
button"));
[Link]();

// Define the expected URL of the home page


String expectedUrl =
"[Link]

// Wait for the expected URL to be loaded


WebDriverWait wait = new WebDriverWait(driver,
[Link](10));
[Link]([Link](expectedUrl));

// Get the current URL after login


String currentUrl = [Link]();

if([Link](expectedUrl)) {
[Link]("Navigation to home page was
successful!");
}

// Quit the WebDriver instance


[Link]();

### 9 X paths

import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];
import [Link];
import [Link];
import [Link];

public class ProductsAndProductDetailsTest {


public static void main(String args[]) {

try {
[Link]("[Link]",
"PATH_TO_CHROMEDRIVER");
// Open the Chrome Browser
WebDriver driver = new ChromeDriver();

// Open the NxtTrendz login page


[Link]("[Link]

// Find and fill in the form fields


WebElement usernameEl =
[Link]([Link]("//input[@id='username']"));
[Link]("rahul");
WebElement passwordEl =
[Link]([Link]("//input[@id='password']"));
[Link]("rahul@2021");

WebElement buttonEl =
[Link]([Link]("//button[@type='submit']"));
[Link]();

// Define the expected URL of the home page


String homePageUrl =
"[Link]

// Wait for the expected URL to be loaded


WebDriverWait wait = new WebDriverWait(driver,
[Link](10));

[Link]([Link](homePageUrl));

// Get the current URL after login


String currentUrl = [Link]();

if ([Link](homePageUrl)) {
[Link]("Navigation to home page was
successful!");
} else {
[Link]("Navigation to home page
failed!");
}

// Find and click on the "Shop Now" button


WebElement shopNowButtonEl =

[Link]([Link]("//button[@class='shop-now-
button']"));
[Link]();

// Define the expected URL of the products page


String productsPageUrl =
"[Link]

// Get the current URL after navigation to products


page
currentUrl = [Link]();
if ([Link](productsPageUrl)) {
[Link]("Navigation to products page
was successful!");
}

//Wait until elements are displayed

[Link]([Link](B
[Link]("//li[@class='product-item']")));

// Verify the display of products on the products page


List<WebElement> products =
[Link]([Link]("//li[@class='product-
item']"));

if ([Link]() > 0) {
[Link]("Products are displayed
successfully on the products page: " + [Link]());

// Select Product with text Minifigures


WebElement productNameEle =
[Link]([Link]("//h1[text()='Minifigures']"));
String expectedProductTitle =
[Link]();
[Link](expectedProductTitle);

[Link]();

String productDetailsUrl =
"[Link]

[Link]([Link](productDetailsUrl));

String currentUrl = [Link]();


if ([Link](productDetailsUrl)) {
[Link]("Navigation to product
details page is successful!");
}

[Link]([Link](B
[Link]("//div[@class='pro-details-success-view']")));
WebElement productTitleElement =
[Link]([Link]("//h1[contains(text(),'Minifig')
]"));
String actualProductTitle =
[Link]();
if
([Link](actualProductTitle)) {
[Link]("Product Name is - " +
actualProductTitle);
} else {
[Link]("Actual product name is not
same as expected product name" + actualProductTitle);
}

String expectedDesc = "Collect all mystery mini-


figures in the new series 11 and grow your LEGO Minifigure
Collection. Each mini-figure comes in a sealed “mystery”
bag with its accessories, display plate, and collector’s
booklet. Only 1 of 16 individual mini-figures will be
available in each “mystery” bag.";

if ([Link](actualProductDesc)) {
[Link]("Description is - " +
actualProductDesc);
} else {
[Link]("Actual description is not
same as expected description" + actualProductDesc);
}

} else {
[Link]("No products found on the
products page.");
}

// Close the browser


[Link]();
} catch (Exception e) {
[Link]("An exception occurred: " +
[Link]());
}
}
}
#10
HTML DOM.

For example, consider the current node as the

<div>
element with the class attribute value of
book
at position
2
. The ancestors of the current node are the
<div>
element with the class name
bookstore
,
<body>
element, and the
<html>
element. We use the below XPath expressions to select the desired elements,
Desired element XPath expression

<div>

element with the class name //div[@class='book'][2]/ancestor::*[position() =

bookstore

<body>
//div[@class='book'][2]/ancestor::*[position() =
element

<html>
//div[@class='book'][2]/ancestor::*[position() =
element

From the above table, we can understand that the position while using the
ancestor axis will be in the increasing order from bottom to top of the
HTML DOM. Whereas, the position while using the descendant axis will be
in the increasing order from top to bottom of the HTML DOM as shown
below,

Desired element XPath expression

<h1>

element with class name //div[@class='book'][2]/descendant::*[position() =

title

<div> //div[@class='book'][2]/descendant::*[position() =

element with class name


Desired element XPath expression

book-details

<p>

element with class name //div[@class='book'][2]/descendant::*[position() =

author

<div>

element with class name //div[@class='book'][2]/descendant::*[position() =

year

<div>

element with class name //div[@class='book'][2]/descendant::*[position() =

price

Even though the element is at the first position in the DOM, we have to
start counting the position from the current node. We have to just
remember that while using the

position()
function with XPath axes,

## 11 css

/* Applying styles based on class name */


.myClass {
color: blue;
font-size: 16px;
}

/* Applying styles based on tag name */


p{
font-weight: bold;
}

/* Applying styles based on id */


#myId {
background-color: yellow;
}

## css2

Verify the display of jobs on the jobs page


List<WebElement> jobs =
[Link]([Link]("li[class*='job-it']"));
//
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];
import [Link];

import [Link];
import [Link];

public class JobbyAppTest {

public static void main(String[] args){

// Set the path to the ChromeDriver executable


[Link]("[Link]",
"PATH_TO_CHROMEDRIVER");
// Open Chrome Browser
WebDriver driver = new ChromeDriver();

// Navigate to the login page


[Link]("[Link]

// Find and fill in the form fields


WebElement usernameEl =
[Link]([Link]("input#userNameInput"))
;
[Link]("rahul");

WebElement passwordEl =
[Link]([Link]("input#passwordInput"));
[Link]("rahul@2021");

WebElement buttonEl =
[Link]([Link]("button[type='submit']"))
;
[Link]();
// Define the expected URL of the home page
String homePageUrl=
"[Link]

// Wait for the expected URL to be loaded


WebDriverWait wait = new WebDriverWait(driver,
[Link](10));
[Link]([Link](homePageUrl));

// Get the current URL and verify redirection to home


page
String currentUrl = [Link]();

if([Link](homePageUrl)){
[Link]("Navigation to home page is
successful!");
}

// Find and click on the "Find Jobs" button


WebElement findJobsButtonEl =
[Link]([Link]("[Link]-jobs-
button"));
[Link]();

// Define the expected URL of the home page


String jobsPageUrl=
"[Link]

// Wait for the expected URL to be loaded


[Link]([Link](jobsPageUrl));

// Get the current URL and verify redirection to jobs


page
currentUrl = [Link]();

if([Link](jobsPageUrl)){
[Link]("Navigation to jobs page is
successful!");
}else {
[Link]("Navigation to jobs page failed!");
}

[Link]([Link](B
[Link]("[Link]-list")));

// Verify the display of jobs on the jobs page


List<WebElement> jobs =
[Link]([Link]("li[class*='job-it']"));

if ([Link]() > 0) {
[Link]("Jobs are displayed successfully
on the jobs page: "+ [Link]());
} else {
[Link]("No Jobs found on the jobs
page.");
}

// Close the browser


[Link]();
}
}

##css3
XPath Axes vs CSS Combinators

CSS combinator Selector XPath Syntax CSS Selector Synta

child parentElement/child::* parentElement > childEl

descendant parentElement/descendant::* parentElement *

adjacent-sibling Doesn’t support element + sibling elem

general-sibling /following-sibling::* element ~ sibling elem

Here, X

import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];
import [Link];
import [Link];
import [Link];

public class JobbyAppTest {

public static void main(String[] args) {

// Set the path to the ChromeDriver executable


[Link]("[Link]",
"/home/nxtwavetech/Downloads/chromedriver_linux64/c
hromedriver");

// Open Chrome Browser


WebDriver driver = new ChromeDriver();

// Navigate to the login page


[Link]("[Link]

// Find and fill in the form fields


WebElement usernameEl =
[Link]([Link]("input#userNameInput"))
;
[Link]("rahul");

WebElement passwordEl =
[Link]([Link]("input#passwordInput"));
[Link]("rahul@2021");

WebElement buttonEl =
[Link]([Link]("button[type='submit']"))
;
[Link]();

// Define the expected URL of the home page


String homePageUrl =
"[Link]

// Wait for the expected URL to be loaded


WebDriverWait wait = new WebDriverWait(driver,
[Link](10));
[Link]([Link](homePageUrl));
// Get the current URL and verify redirection to home
page
String currentUrl = [Link]();

if ([Link](homePageUrl)) {
[Link]("Navigation to home page is
successful!");
}

// Find and click on the "Find Jobs" button


WebElement findJobsButtonEl =
[Link]([Link]("[Link]-jobs-
button"));
[Link]();

// Define the expected URL of the home page


String jobsPageUrl =
"[Link]

// Wait for the expected URL to be loaded


[Link]([Link](jobsPageUrl));

// Get the current URL and verify redirection to jobs


page
currentUrl = [Link]();

if ([Link](jobsPageUrl)) {
[Link]("Navigation to jobs page is
successful!");
}

[Link]([Link](B
[Link]("[Link]-list")));

// Verify the display of jobs on the jobs page


List<WebElement> jobs =
[Link]([Link]("li[class *= 'job-it']"));

if ([Link]() > 0) {
[Link]("Jobs are displayed successfully
on the jobs page: " + [Link]());
String expectedRating = "4";
WebElement jobRatingEle =
[Link]([Link]("a[href='/jobs/bb95e51b-
b1b2-4d97-bee4-1d5ec2b96751'] > li [Link]"));
String rating = [Link]();

if ([Link](rating)) {
[Link]("Rating is 4");
} else {
[Link]("Job Rating is not as
expected");
}

} else {
[Link]("No Jobs found on the jobs
page.");
}

// Close the browser


[Link]();
}
}

###10
It returns an instance of the

TargetLocator
interface, which provides methods for switching the /control/focus between windows, frames
and alerts, etc.
Method Decription

alert() Switches to the currently active alert

frame() Selects a frame based on index, name or id

window() Selects a window based on the name or handle

In this unit, we will learn about

alert()
method.

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import
[Link];
import [Link];

import [Link];

public class AlertTest {


public static void main(String args[]) {
try {
// Set the path to the ChromeDriver executable
[Link]("[Link]",
"PATH_TO_CHROMEDRIVER");

// Launch the Chrome browser


WebDriver driver = new ChromeDriver();

// Open the Jobby App login page


[Link]("[Link]
// Locate username field
WebElement usernameEl =
[Link]([Link]("input#userNameInput"))
;
[Link]("rahul");

// Locate password field


WebElement passwordEl =
[Link]([Link]("input#passwordInput"));
[Link]("rahul@2021");

// Locate submit button


WebElement buttonEl =
[Link]([Link]("[Link]-button"));
[Link]();

// Define the expected URL of the home page


String expectedUrl =
"[Link]
// Wait for the expected URL to be loaded
WebDriverWait wait = new WebDriverWait(driver,
[Link](10));
[Link]([Link](expectedUrl));

// Get the current URL after login


String currentUrl = [Link]();
if ([Link](expectedUrl)) {
[Link]("Navigation to home page is
successful!");
}

// Locating logout button


WebElement logoutButton =
[Link]([Link]("logout-desktop-btn"));
[Link]();

// Switch control to alert


Alert confirmationAlert = [Link]().alert();
// Get the alert text
[Link]([Link]());

//Accept the alert and logout of the application


[Link]();

String loginUrl =
"[Link]
// Wait for the expected URL to be loaded
[Link]([Link](loginUrl));

// Get the current URL after logout


currentUrl = [Link]();
if ([Link](loginUrl)) {
[Link]("Logout is successful and page
is redirected to login page!");
}

//Close the browser


[Link]();
} catch (Exception e){
[Link]([Link]());
}
}
}

You might also like