Selenium With Java
Selenium With Java
1. What is WebDriver?
2. Role of WebDriver:
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.
username.sendKeys("standard_user");
● Browser Controls:
Manage browser properties, handle windows, navigate back and forward.
driver.manage().window().maximize();
package com.Selenium;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
// 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");
// 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.
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:
Explanation:
● Use the get method to navigate to a specific URL.
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:
Explanation:
● Use the Actions class to perform complex interactions, like mouse
movements.
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.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
// 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");
// close driver
driver.close();
}
}
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.
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.
// Navigate to a website
driver.get("https://www.saucedemo.com/v1/");
5. Output Explanation:
Conclusion:
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");
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();
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);
6. Output Explanation:
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.
Example:
Example:
Example:
WebElement elementByClassName =
driver.findElement(By.className("btn-contact"));
Example:
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:
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:
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']
WebElement elementByXpath =
driver.findElement(By.xpath("//input[@type='checkbox'][@value='']"));
Key Concepts:
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.
1. Buttons:
Locating a Button:
Clicking a Button:
btnSignIn.click();
2. Text Fields:
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:
WebElement rdoRights =
driver.findElement(By.cssSelector("input[type='radio'][value='admin']"));
rdoRights.click();
5. Dropdowns:
● Locating a Dropdown:
Select dropdown = new Select(driver.findElement(By.id("countrySelect")));
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.
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:
2. sendKeys() Method:
Purpose:
Enters text into input fields, text areas, or any element that accepts keyboard input.
Example:
3. getText() Method:
Purpose:
Retrieves the visible text of an element.
Example:
4. getAttribute() Method:
Purpose:
Retrieves the value of the specified attribute of an element.
Example:
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.
● 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'
● Checking/Unchecking a Checkbox:
chkInterests.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.
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.
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.
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:
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):
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.
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:
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();
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
Practice creating and running simple tests with both TestNG and
JUnit.