0% found this document useful (0 votes)
38 views25 pages

Selenium With Java

Uploaded by

Jaideep Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
38 views25 pages

Selenium With Java

Uploaded by

Jaideep Bhagat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

Module 3: Selenium Fundamentals

3.1 Install Java Development Kit (JDK)

Download and install the latest version of JDK.

Set up the environment variables for Java.

3.2 SetUp Eclipse IDE

Download and install the Eclipse IDE.

Configure Eclipse for Java development.

3.3 Setup Selenium WebDriver with Java

Download the Selenium WebDriver Java bindings.

Create a new Java project in Eclipse.

Add Selenium JAR files to your project.

Understand the concept of WebDriver and its role in Selenium.

Selenium WebDriver is a powerful tool for automating web applications. It provides a


programming interface for interacting with web browsers. Let's break down the key
concepts:

1. What is WebDriver?

WebDriver is a browser automation framework in Selenium.


It allows you to programmatically control a web browser and automate user actions.

2. Role of WebDriver:

● Browser Automation: WebDriver facilitates the automation of actions


performed in a web browser, such as clicking buttons, filling forms, and
navigating between pages.
● Cross-Browser Testing: WebDriver supports multiple browsers like Chrome,
Firefox, Safari, and more. It enables cross-browser testing, ensuring your web
application works consistently across different browsers.

3. Key Features:

● Navigation:
WebDriver allows you to navigate to different URLs.

driver.get("https://www.saucedemo.com/v1/");

● Locating Elements:
It provides methods to locate HTML elements on a web page.

WebElement username = driver.findElement(By.id("user-name"));

● Interacting with Elements:


You can perform actions like clicking buttons, typing text, etc.

username.sendKeys("standard_user");

● Browser Controls:
Manage browser properties, handle windows, navigate back and forward.

driver.manage().window().maximize();

4. Sample WebDriver Code:

Here's a simple example to illustrate the basic usage of WebDriver in Java:

package com.Selenium;

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

public class SeleniumTest {


public static void main(String[] args) {
// Setting system property for chrome driver
System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver(); // launch Chrome browser
driver.get("https://www.saucedemo.com/v1/"); // enter URL
System.out.println(driver.getTitle()); // get title of the page

// Maximize window
driver.manage().window().maximize();
// enter username
WebElement username = driver.findElement(By.id("user-name"));
username.sendKeys("standard_user");

// enter password
WebElement password = driver.findElement(By.id("password"));
password.sendKeys("secret_sauce");

// click on login button


WebElement loginButton =
driver.findElement(By.id("login-button"));
loginButton.click();

//wait for 5 seconds


try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

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

5. Conclusion:
● WebDriver is a crucial component in Selenium for automating browser
interactions.
● It empowers testers and developers to create robust and efficient automated
tests for web applications.
● Understanding WebDriver's capabilities is fundamental for effective Selenium
automation.
● Remember to replace "path/to/chromedriver.exe" with the actual path where
you've downloaded the ChromeDriver executable.

Familiarize yourself with the structure of a basic Selenium script.

A Selenium script is composed of several elements that work together to automate


interactions with a web application. Let's break down the structure:

1. Importing Selenium Libraries:

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

Explanation:
● Import the necessary Selenium WebDriver libraries.
● These libraries provide classes and methods to interact with web browsers.

2. Setting up WebDriver:

System.setProperty("webdriver.chrome.driver",
"path/to/chromedriver");
WebDriver driver = new ChromeDriver(); // launch Chrome browser

Explanation:
● Set the system property to the location of the ChromeDriver executable.
● Initialise a WebDriver instance, in this case, a ChromeDriver.

3. Navigating to a URL:

driver.get("https://www.saucedemo.com/v1/"); // enter URL

Explanation:
● Use the get method to navigate to a specific URL.

4. Interacting with Web Elements:

WebElement username = driver.findElement(By.id("user-name"));


username.sendKeys("standard_user");

Explanation:
● Locate a web element using a specific locator (e.g., ID, name, XPath).
● Interact with the element, like sending keys (typing text).

5. Performing Actions:

Actions actions = new Actions(driver);


actions.moveToElement(element).perform();

Explanation:
● Use the Actions class to perform complex interactions, like mouse
movements.

6. Assertions and Verifications:

String pageTitle = driver.getTitle();


Assert.assertEquals(pageTitle, "Expected Title");

Explanation:
● Capture information from the web page, such as the title.
● Use assertions to verify that the actual result matches the expected result.
7. Closing the Browser:

driver.close();

Explanation:
● Terminate the WebDriver session, closing the associated browser.

8. Sample Selenium Script:

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

public class SeleniumTest {


public static void main(String[] args) {
// Setting system property for chrome driver
System.setProperty("webdriver.chrome.driver",
"/path/to/chromedriver");
WebDriver driver = new ChromeDriver(); // launch Chrome browser
driver.get("https://www.saucedemo.com/v1/"); // enter URL
System.out.println(driver.getTitle()); // get title of the page

// Maximize window
driver.manage().window().maximize();

// assertion
String expectedTitle = "Swag Labs";
String actualTitle = driver.getTitle();
if (expectedTitle.equals(actualTitle)) {
System.out.println("Test passed");
}
else {
System.out.println("Test failed");
}

// enter username
WebElement username = driver.findElement(By.id("user-name"));
username.sendKeys("standard_user");

// enter password
WebElement password = driver.findElement(By.id("password"));
password.sendKeys("secret_sauce");

// click on login button


WebElement loginButton =
driver.findElement(By.id("login-button"));
loginButton.click();

//wait for 5 seconds


try {
Thread.sleep(5000); // wait for 5 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}

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

9. Output Explanation: This script,


a. opens a Chrome browser and
b. navigates to https://www.saucedemo.com/v1/,
c. maximizes the browser,
d. then enters username and password and clicks on login button
e. waits for 5 seconds to close the browser

10. Conclusion:
● Understanding the structure of a Selenium script is essential for creating
effective and maintainable automated tests.
● Each section plays a crucial role in automating interactions with a web
application.
● Remember to replace "path/to/chromedriver.exe" with the actual path where
you've downloaded the ChromeDriver executable.

3.4 Navigating with Selenium WebDriver

Learn how to open a browser using WebDriver.

One of the fundamental steps in Selenium automation is opening a web browser


using WebDriver. Let's break down this process:

1. Importing Selenium Libraries:

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

Explanation:
● Import the necessary Selenium WebDriver libraries.
● These libraries provide classes and methods to interact with web browsers.

2. Setting up WebDriver:

System.setProperty("webdriver.chrome.driver", "path/to/chromedriver.exe");
WebDriver driver = new ChromeDriver();
Explanation:
● Set the system property to the location of the ChromeDriver executable.
● Initialize a WebDriver instance, in this case, a ChromeDriver.

3. Opening a Browser:

driver.get("https://www.example.com");

Explanation:
● Use the get method to navigate to a specific URL.
● This step opens the specified URL in the web browser.

4. Sample Selenium Script:

import org.openqa.selenium.WebDriver; // import webdriver


import org.openqa.selenium.chrome.ChromeDriver; // import chrome driver

public class OpenBrowserExample {


public static void main(String[] args) {
// Set the path of chromedriver
String path = "path/to/chromedriver";
System.setProperty("webdriver.chrome.driver", path);

// Create an instance of ChromeDriver


WebDriver driver = new ChromeDriver();

// Navigate to a website
driver.get("https://www.saucedemo.com/v1/");

// Close the browser


driver.quit();
}
}

5. Output Explanation:

This script opens a Chrome browser and navigates to


"https://www.saucedemo.com/v1/" After completing the task, it closes the browser.

Conclusion:

● Opening a browser is the initial step in Selenium automation.


● The WebDriver interface and browser-specific drivers, like ChromeDriver, play a
crucial role in this process.
● Remember to replace "path/to/chromedriver.exe" with the actual path where
you've downloaded the ChromeDriver executable.
Understand navigation methods like get(), navigate().to(),
navigate().back(), and navigate().forward().

Navigation methods in Selenium WebDriver allow you to control the browser's


navigation flow. Let's explore these methods and understand their usage:

1. get(String url) Method:

Explanation:
● The get method is used to navigate to a specific URL.
● It waits for the page to load completely before proceeding.
Example:

driver.get("https://www.example.com");

2. navigate().to(String url) Method:

Explanation:
● Similar to the get method, navigate().to is used for navigation to a specific
URL.
● It can be used interchangeably with get.
Example:

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

3. navigate().back() Method:

Explanation:
● navigate().back() is used to navigate back to the previous page in the
browser's history.
Example:

// Navigate to a page
driver.get("https://www.example.com");
// Navigate to another page
driver.get("https://www.example2.com");
// Go back to the previous page
driver.navigate().back();

4. navigate().forward() Method:

Explanation:
● navigate().forward() is used to move forward to the next page in the browser's
history after using navigate().back().
Example:

// Navigate to a page
driver.get("https://www.example.com");
// Navigate to another page
driver.get("https://www.example2.com");
// Go back to the previous page
driver.navigate().back();
// Go forward to the next page
driver.navigate().forward();

5. Sample Selenium Script:

package com.Selenium;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class NavigationExample {
public static void main(String[] args) {
// Set the path of chromedriver
String path = "path/to/chromedriver";
System.setProperty("webdriver.chrome.driver", path);

// Create an instance of ChromeDriver


WebDriver driver = new ChromeDriver();

// Navigate to a website using get() method


driver.get("https://www.saucedemo.com/v1/");

// Navigate to another website using navigate().to() method


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

// Go back to the previous page using navigate().back() method


driver.navigate().back();

// Go forward to the next page using navigate().forward() method


driver.navigate().forward();

// Close the browser


driver.close();
}
}

6. Output Explanation:

This script opens a Chrome browser, navigates to "https://www.saucedemo.com/v1/”


then to "https://www.google.com/" goes back to the previous page, goes forward to
the next page, and finally closes the browser.

Conclusion:
● Navigation methods provide flexibility in controlling the flow of browser
navigation.
● get(), navigate().to(), navigate().back(), and navigate().forward() are essential
for seamless web automation.
● Remember to replace "path/to/chromedriver.exe" with the actual path where
you've downloaded the ChromeDriver executable.

3.5 Locating Elements in Selenium

Explore different methods for locating elements: by ID, by name, by


class name, by tag name, by link text, and by partial link text.

In Selenium WebDriver, locating elements on a web page is crucial for interaction.


Here, we will explore various methods to locate elements:

1. By ID: Locates an element using its unique ID attribute.

Example:

WebElement elementById = driver.findElement(By.id("username"));

2. By Name: Locates an element using its "name" attribute.

Example:

WebElement elementByName = driver.findElement(By.name("password"));

3. By Class Name: Locates an element using its class name.

Example:

WebElement elementByClassName =
driver.findElement(By.className("btn-contact"));

4. By Tag Name: Locates elements based on their HTML tag.

Example:

WebElement elementByTagName = driver.findElement(By.tagName("a"));

5. By Link Text: Locates a link element by the exact text in the link.

Example:
WebElement elementByLinkText = driver.findElement(By.linkText("terms and
conditions"));

6. By Partial Link Text: Locates a link element using a part of its text.

Example:

WebElement elementByPartialLinkText =
driver.findElement(By.partialLinkText("Free"));

Conclusion:

Understanding different methods for locating elements is crucial for effective


automation testing. By using these methods, you can interact with various elements
on a web page and perform desired actions during testing.

Understand the concept of CSS selectors and XPath for element


identification.

In Selenium WebDriver, CSS selectors and XPath are powerful techniques for
locating elements on a web page. Let's delve into the concepts of CSS selectors and
XPath:

1. CSS Selectors:

Definition:
CSS selectors are patterns used to select and style HTML elements. In Selenium,
they are employed to identify and locate elements on a web page.

Syntax:

Basic Syntax: tagname[attribute='value']


Example: input[name='username']

Example Selenium Usage:

WebElement elementByCssSelector =
driver.findElement(By.cssSelector("input[type='radio'][value='married']"));

2. XPath:

Definition:
XPath is a language used for navigation through XML documents. In Selenium,
XPath expressions can be used to locate elements on a web page.
Syntax:
Absolute XPath: /html/body/div[1]/input
Relative XPath: //input[@name='username']

Example Selenium Usage:

WebElement elementByXpath =
driver.findElement(By.xpath("//input[@type='checkbox'][@value='']"));

Key Concepts:

● Choosing Between CSS Selectors and XPath:


○ CSS selectors are often faster and more readable.
○ XPath is more versatile and can traverse both upwards and downwards in
the DOM.
● Inspecting Elements in Browser Developer Tools:
○ Right-click on an element and choose "Inspect" to view its HTML structure.
○ Right-click on an HTML element in the "Elements" tab and choose "Copy" to
copy its CSS selector or XPath.

Conclusion:

Understanding CSS selectors and XPath is crucial for effectively locating elements
during Selenium test automation. Depending on the scenario, you can choose the
most suitable method for element identification, improving the robustness and
readability of your automation scripts.

3.6 Interacting with Web Elements

Learn how to interact with various types of web elements, like


buttons, text fields, checkboxes, and radio buttons.

Selenium WebDriver provides methods to interact with different types of web


elements. Here's a guide on how to handle common elements like buttons, text
fields, checkboxes, and radio buttons:

1. Buttons:

Locating a Button:

WebElement btnSignIn = driver.findElement(By.id("signInBtn"));

Clicking a Button:
btnSignIn.click();

2. Text Fields:

Locating a Text Field:

WebElement txtUserName = driver.findElement(By.id("username"));

Typing into a Text Field:

txtUserName.sendKeys("administrator");

3. Checkboxes:

Locating a Checkbox:

WebElement chkTerms =
driver.findElement(By.xpath("//input[@type='checkbox'][@name='terms']"));

Checking/Unchecking a Checkbox:

chkTerms.click();

4. Radio Buttons:

Locating a Radio Button:

WebElement rdoRights =
driver.findElement(By.cssSelector("input[type='radio'][value='admin']"));

Selecting a Radio Button:

rdoRights.click();

5. Dropdowns:

Handling Dropdowns (Select Element):

● Locating a Dropdown:
Select dropdown = new Select(driver.findElement(By.id("countrySelect")));

● Selecting Options from Dropdown:


dropdown.selectByVisibleText("United States");

Conclusion:
Interacting with web elements is a fundamental aspect of Selenium test automation.
By understanding how to locate and perform actions on buttons, text fields,
checkboxes, radio buttons, and dropdowns, you can build robust and effective
automation scripts for your web applications.

Understand methods like click(), sendKeys(), getText(), and


getAttribute().

Selenium WebDriver provides several essential methods for interacting with web
elements. Let's explore some of the commonly used methods:

1. click() Method:

Purpose:
Used to simulate a mouse click on an element, like a button or a link.

Example:

WebElement SignInBtn = driver.findElement(By.id("signInBtn"));


SignInBtn.click();

2. sendKeys() Method:

Purpose:
Enters text into input fields, text areas, or any element that accepts keyboard input.

Example:

WebElement elementById = driver.findElement(By.id("username"));


elementById.sendKeys("jaideepbhagat");

3. getText() Method:

Purpose:
Retrieves the visible text of an element.

Example:

WebElement elementByTagName = driver.findElement(By.tagName("a"));


String textInElement = elementByTagName.getText();

4. getAttribute() Method:
Purpose:
Retrieves the value of the specified attribute of an element.

Example:

WebElement imageElement = driver.findElement(By.tagName("img"));


String srcAttribute = imageElement.getAttribute("src");

Additional Notes:
● Waiting for Elements:
○ It's often good practice to use implicit or explicit waits to ensure the
element is present and clickable before performing actions.
● Handling Dynamic Content:
○ Elements rendered dynamically may require additional strategies, like
waiting for specific conditions or using dynamic locators.

Conclusion:

Understanding and effectively using these methods are fundamental for Selenium
WebDriver automation. Whether clicking buttons, entering text, retrieving visible text,
or extracting attributes, these methods empower you to interact with web elements
efficiently during test automation.

3.7 Advanced Interactions and Waits

Explore advanced interactions such as handling dropdowns,


working with checkboxes, and selecting from radio buttons.

Advanced interactions in Selenium WebDriver involve handling dropdowns, working


with checkboxes, and selecting from radio buttons. Let's dive into these topics:

1. Handling Dropdowns (Select Element):


● Locating a Dropdown:

Select countryDropdown = new


Select(driver.findElement(By.name("country")));

● Selecting Options:
● By Index:
countryDropdown.selectByIndex(2); // select 3rd option, index starts
at 0

● By Visible Text:
countryDropdown.selectByVisibleText("Sri Lanka");

● By Value:
countryDropdown.selectByValue("US"); // Assumes the option has a
'value' attribute with the value 'us'

2. Working with Checkboxes:


● Locating a Checkbox:
WebElement chkInterests =
driver.findElement(By.cssSelector("input[type='checkbox'][value='Books
']"));

● Checking/Unchecking a Checkbox:
chkInterests.click();

3. Selecting from Radio Buttons:


● Locating a Radio Button:
WebElement rdoGender =
driver.findElement(By.xpath("//input[@type='radio'][@value='Male']"));

● Selecting a Radio Button:


rdoGender.click();

Additional Notes:
● Handling Multiple Windows or Frames:
● For elements within frames or pop-up windows, ensure that you switch
to the correct context using driver.switchTo().frame() or
driver.switchTo().window().
● Verifying Selections:
● After interacting with elements, it's good practice to verify the selected
options or states to ensure the desired actions were performed.

Conclusion:
Mastering advanced interactions in Selenium WebDriver allows you to handle
complex user interfaces with dropdowns, checkboxes, and radio buttons effectively.
These skills are crucial for creating comprehensive and reliable automated tests for
your web applications.
Understand the importance of implicit and explicit waits in
Selenium.
Selenium interacts with web elements on a page, and the loading times of these
elements can vary. To handle this variability, Selenium provides implicit and explicit
waits.

1. Implicit Waits:
Implicit waits are set globally for the entire duration of the WebDriver's instance.
They instruct the WebDriver to wait for a certain amount of time before throwing an
exception if an element is not immediately available. This helps in dealing with
synchronization issues.

● Setting an Implicit Wait:

WebDriver driver = new ChromeDriver();


// Set implicit wait for 10 seconds
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

2. Explicit Waits:
Explicit waits are more specific, allowing you to wait for certain conditions before
proceeding with the execution. This provides better control over synchronization
issues.

● Setting an Explicit Wait:

WebDriverWait wait = new WebDriverWait(driver, 10);


WebElement address =
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("select
")));

Importance:
​ Synchronization:
● Web pages may load elements at different rates. Without waits,
Selenium may attempt to interact with an element before it's available,
leading to errors.
​ Dynamic Content:
● Websites often use AJAX or other dynamic techniques to load content
asynchronously. Explicit waits ensure elements are ready before
interacting.
​ Improved Test Stability:
● By incorporating waits, your tests become more resilient to changes in
load times and dynamic content, enhancing the stability of your test
scripts.
​ Efficiency:
● Waits prevent unnecessary delays by allowing your script to proceed as
soon as the required conditions are met.

Conclusion:
Understanding and implementing implicit and explicit waits in Selenium is crucial for
building robust and stable test automation scripts. These features enhance
synchronization, making your tests more reliable in various web environments.

Module 4 Advance Selenium and Practice

4.1 Synchronization in Selenium

Understand the importance of synchronization in Selenium.

In Selenium automation, synchronization is absolutely essential for reliable test


execution. It ensures your test scripts and the web application you're testing are in
step with each other. Here's a breakdown of why synchronization is important:

● Timing Issues: Web pages load at different speeds depending on factors


like internet connection, server load, and page complexity. Selenium scripts
run at a fixed pace. Without synchronization, your script might try to interact
with an element that hasn't loaded yet, leading to errors like
"NoSuchElementException" or "ElementNotVisibleException".
● Dynamic Content: Modern web applications heavily rely on AJAX and
JavaScript to update content dynamically. This means elements might appear
or disappear after the initial page load. If your script tries to find an element
before it's been added to the DOM (Document Object Model), it will fail.
● State Changes: Certain actions, like clicking a button, can trigger events that
change the application's state. If your script performs an action before the
state change is complete, it might interact with outdated information.
Synchronization ensures your script waits for the application to reach a stable
state before proceeding.
How to handle synchronization issues.

There are several ways to handle synchronization issues in Selenium WebDriver to


ensure your tests interact with elements that are fully loaded and ready for action.
Here are the main approaches:

1. Implicit Waits:

● Concept: A global wait that sets a timeout for all element finding and
interaction operations throughout your script. If Selenium can't locate an
element within the specified timeframe (in seconds), it throws an exception.
● Advantages:
○ Easy to implement - just one line of code sets a wait time for the entire
script.
○ Useful for basic test cases where element load times are predictable.
● Disadvantages:
○ Inefficient for complex scenarios: If some elements load quickly and
others take longer, the entire script waits for the maximum timeout for
all elements.
○ Less control: You cannot define specific conditions for waiting. Implicit
waits simply wait for the element to exist, not necessarily for it to be
usable (clickable, visible).
● Example (Java):

2. Explicit Waits:

● Concept: Offer a more targeted, condition-based approach. You wait for a


specific condition to be met before proceeding with the next step in your
script. Selenium provides various ExpectedConditions like
presenceOfElementLocated, visibilityOfElementLocated, and
elementToBeClickable.
● Advantages:
○ Increased precision: You wait only for the elements you need and
only until they meet the desired condition (clickable, visible, etc.).
○ Improved test execution time: Scripts don't wait unnecessarily for
slow elements if others are readily available.
● Disadvantages:
○ Requires more code: You need to define the wait condition and
element locator for each explicit wait statement.
● Example (Java):
WebDriverWait wait = new WebDriverWait(driver,
Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.classN
ame("textarea")));

3. Fluent Waits:

● Concept: Combine the best aspects of implicit and explicit waits, offering
flexible control over the waiting process. They allow you to configure various
parameters:
○ Timeout: The maximum time the wait will continue searching for the
condition.
○ Polling Interval: How often the wait checks for the condition (e.g.,
every 500 milliseconds).
○ Ignored Exceptions: Specify exceptions to ignore during polling (e.g.,
StaleElementReferenceException) to prevent unnecessary test
failures.
● Advantages:
○ Fine-tuned control: You can tailor the wait behavior to your specific
needs.
○ Improved execution time: Waits only as long as necessary for the
condition.
○ Enhanced test stability: Ignoring transient exceptions during polling
leads to more reliable tests.
● Example (Java):

FluentWait<WebDriver> waitt = new FluentWait<WebDriver>(driver)


.withTimeout(Duration.ofSeconds(10))
.pollingEvery(Duration.ofSeconds(2))
.ignoring(Exception.class);

Choosing the Right Wait for the Job

The best wait strategy depends on your test case complexity and needs:

● For simple scenarios with predictable element load times, implicit waits
might suffice.
● For complex scenarios with dynamic content or asynchronous operations,
explicit waits with specific ExpectedConditions are preferred.
● For scenarios with precise control requirements or handling transient
exceptions, Fluent Waits offer the most flexibility and power.

Additional Tips:
● Identify synchronization points: Analyze your application and pinpoint
areas where element visibility or state changes might require waiting (e.g.,
after clicking a button or submitting a form).
● Combine wait strategies: You can use a combination of implicit waits as a
baseline and explicit waits for critical actions.
● Minimize unnecessary waits: Avoid using Thread.sleep() as it
introduces unnecessary delays regardless of whether elements are loaded.

By effectively using synchronization techniques, you can ensure your Selenium tests
are robust, reliable, and less prone to errors caused by timing mismatched.

4.2 Handling Frames

Understand switching between frames and handling elements


inside frames.

Frames, also known as iframes, are sometimes used in web pages to embed content
from other sources. Selenium provides functionalities to switch between frames and
interact with elements within them. Here's how to handle frames effectively:

1. Identifying Frames:

There's no direct way to identify all frames on a page using Selenium. However, you
can use techniques like inspecting the page source for <iframe> tags or using
browser developer tools to locate frames visually.

2. Switching to Frames:

The driver.switchTo() method offers various ways to switch the focus to a


specific frame:

● switchTo().frame(String frameNameOrId): Switches to the frame identified


by its name or ID attribute (if available).
driver.switchTo().frame("iframe_level");

● switchTo().frame(int index): Switches to the frame at the specified index


(zero-based indexing).

driver.switchTo().frame(1); // Switches to the second frame


(index starts from 0)

● switchTo().frame(WebElement frameElement): Switches to the frame


represented by the provided WebElement (assuming it points to an iframe
element).
WebElement iframeElement =
driver.findElement(By.xpath("//iframe[@src='form.html']"));
driver.switchTo().frame(iframeElement);

3. Locating and Interacting with Elements Within Frames:

Once you've switched the focus to the desired frame, you can use the same
techniques like findElement and interaction methods (click, sendKeys, etc.) to
locate and interact with elements within the frame.

WebElement chkLevel =
driver.findElement(By.cssSelector("input[type='radio'][value='Inte
rmediate']"));
chkLevel.click();

4. Switching Back to Parent Frame:

After interacting with elements inside the frame, you might need to switch back to the
parent frame. Use driver.switchTo().parentFrame() to achieve this.

driver.switchTo().parentFrame();

5. Important Considerations:

● Nested Frames: If you have nested frames (frames within other frames),
you'll need to switch frames sequentially to reach the desired element.
● Default Content: You can use driver.switchTo().defaultContent()
to switch back to the main document from any nested frame level.

Example (Java):

Java

WebElement iframeElement =
driver.findElement(By.xpath("//iframe[@src='advertisement.html
']"));
driver.switchTo().frame(iframeElement); // Switch to the frame

WebElement closeAdButton =
driver.findElement(By.id("closeAd"));
closeAdButton.click(); // Click the close button within the
frame

driver.switchTo().parentFrame(); // Switch back to the parent


frame
By understanding these techniques and considerations, you can effectively handle
frames and interact with elements within them in your Selenium tests. Remember,
frames are becoming less common in modern web development, but the ability to
handle them can still be useful for older applications or specific scenarios.
4.3 Handling Windows and Tabs

Explore handling multiple browser windows and tabs.

Learn techniques for switching between windows and tabs.

Understand how to perform actions in different browser instances.

Practice synchronization with different scenarios to ensure stability


in your scripts.

Experiment with various types of dropdowns and frames on web


pages.

4.4 Introduction to TestNG

Understand the role of TestNG in Java test automation.

Learn how to install and configure TestNG in your project.

Explore TestNG annotations and their significance.

4.5 TestNG Features and Test Suites

Explore TestNG features such as parameterization, grouping, and


dependencies.

Learn how to create and run test suites in TestNG.

4.6 Introduction to JUnit

Understand the basics of JUnit and its role in Java testing.

Learn how to set up JUnit in your project.

Practice creating and running simple tests with both TestNG and
JUnit.

Explore the reporting capabilities of TestNG.


4.7 Automation Scripting Basics

Create a simple Selenium script to open a website and perform


basic interactions (e.g., clicking a button or filling a form).

Implement assertions to validate the expected outcomes.

4.8 Advanced Selenium Features

Explore advanced Selenium features like handling cookies,


capturing screenshots, and handling browser navigation history.

Learn about taking screenshots for better debugging.

4.9 Project Integration and Challenges

Integrate Selenium with your existing Java project.

Tackle more complex scenarios, such as handling dynamic


elements or dealing with complex web page structures.

Challenge yourself with a mini-project to reinforce your learning.

Experiment with different locators and strategies for element


identification.

Consider incorporating Page Object Model (POM) for better code


organization.

You might also like