0% found this document useful (0 votes)
56 views12 pages

Selenium Java Cheat Sheet

The document provides code snippets and descriptions for common Selenium tasks like initializing browser drivers, locating elements, handling frames, alerts and windows, and using explicit waits. It includes the syntax for initializing Chrome, Edge, Firefox and Safari drivers and locating elements by id, name, class, tag name, link text, partial link text, css selector and xpath. It also describes methods for switching frames and windows, accepting/dismissing alerts, and expected conditions for explicit waits.

Uploaded by

Carlos
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)
56 views12 pages

Selenium Java Cheat Sheet

The document provides code snippets and descriptions for common Selenium tasks like initializing browser drivers, locating elements, handling frames, alerts and windows, and using explicit waits. It includes the syntax for initializing Chrome, Edge, Firefox and Safari drivers and locating elements by id, name, class, tag name, link text, partial link text, css selector and xpath. It also describes methods for switching frames and windows, accepting/dismissing alerts, and expected conditions for explicit waits.

Uploaded by

Carlos
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

Initialize

Browser Drivers
Browser Syntax
Chrome WebDriver driver = new ChromeDriver();

Edge WebDriver driver = new EdgeDriver();

Firefox WebDriver driver = new FirefoxDriver();

Safari WebDriver driver = new SafariDriver();


Selenium
Locators
Locator Syntax
className [Link]([Link] (“value”))

cssSelector [Link]([Link](“value"))
id [Link]([Link](“value"))
linkText [Link]([Link](“value"))
name [Link]([Link](“value"))
partialLinkText [Link]([Link](“value"))
tagName [Link]([Link] (“value”))

xpath [Link]([Link](“value"))
Switch Method
Types For Frames
Method Description
frame(WebElement element) Selects a frame by WebElement

frame(String nameOrId) Selects a frame by its name or ID

frame(int index) Selects a frame by its (zero-based) index

defaultContent() Selects either first frame or main document

parentFrame() Change focus to the parent context


Frame
Example
Alerts/Pop-Ups

Method Description
accept() Accepts the alert

dismiss() Dismisses / cancels the alert

getText() Gets text from the alert

sendKeys() Types text into the alert


Alert
Example
Log Into
Application
Menu
Company Username

Logo Password

Submit
Button

Pop-Up / Alert
Box

OK CANCEL
Switch Method
Types For Windows
Method Description
getWindowHandle() Gets the window handle of the current window

getWindowHandles() Gets the window handle of all current windows

switchTo().window() Switch focus between windows


Switch Windows
Example
Explicit Wait
Example
Selenium
Waits
Selenium Wait Description
[Link]() (Not a Selenium Wait Method) Causes execution to
sleep for a certain number of milliseconds
Page Load Timeout Sets the wait time for a page to load before throwing
an error
Script Timeout Sets the wait time for JavaScript to execute before
throwing an error
Implicit Wait Determines the wait time to search for an element
before throwing an exception
Explicit Wait Pauses execution until time has expired or an
expected condition is met via WebDriverWait class
Fluent Wait A specialization of Explicit Wait that’s extended by
the WebDriverWait class
Explicit Wait
Expected Conditions
1. alertIsPresent() 9. textToBePresentInElementLocated()

2. elementSelectionStateToBe() 10. textToBePresentInElementValue()

3. elementToBeClickable() 11. titleIs()

4. invisibilityOfTheElementLocated() 12. titleContains()

5. invisibilityOfElementWithText() 13. visibilityOf()

6. presenceOfAllElementsLocatedBy() 14. visibilityOfAllElements()

7. presenceOfElementLocated() 15. visibilityOfAllElementsLocatedBy()

8. textToBePresentInElement() 16. visibilityOfElementLocated()


Select From
Drop Down Code Snippet

Common questions

Powered by AI

To initialize a browser driver using Selenium WebDriver, you can use different commands for different browsers: Chrome uses 'WebDriver driver = new ChromeDriver();', Edge uses 'WebDriver driver = new EdgeDriver();', Firefox uses 'WebDriver driver = new FirefoxDriver();', and Safari uses 'WebDriver driver = new SafariDriver();' .

In Selenium, 'frame(int index)' and 'frame(String nameOrId)' both help select frames, but they differ in selection criteria. 'frame(int index)' selects a frame based on its zero-based index position, which is useful when you know the exact order of frames but not their names or IDs. Conversely, 'frame(String nameOrId)' is more precise as it directly selects a frame using its name or unique ID attribute, making it preferred when identifying frame elements based on their named configuration rather than their position .

The 'switchTo().window()' method in Selenium is crucial for handling scenarios that involve multiple browser windows or tabs. By leveraging this method alongside 'getWindowHandles()', testers can navigate between different windows, ensuring that automation scripts can interact with each correctly. This functionality is vital in testing workflows where opening new windows or switching between tabs is necessary to validate user journeys or interactions requiring multi-window context, such as social media logins or popup-driven site elements .

Selenium has several wait mechanisms: 'Thread.sleep()' causes sleep but isn't a Selenium wait method; 'Page Load Timeout' and 'Script Timeout' set maximum wait times for page loading and JavaScript execution, respectively. 'Implicit Wait' sets a default time for finding elements. 'Explicit Wait' pauses execution until a condition (like 'alertIsPresent()', 'elementToBeClickable()') is met, using 'WebDriverWait'. 'Fluent Wait' is an extension of Explicit Wait, allowing for polling frequency configuration. Explicit waits are more precise than implicit waits, which apply globally .

Explicit waits are generally preferred over 'Thread.sleep()' in Selenium due to their efficiency and flexibility. While 'Thread.sleep()' forces the execution to pause for a fixed time, leading to potential inefficiencies if elements load faster, explicit waits dynamically pause execution until a condition is met, such as element visibility, in a given timeframe. This results in optimized test run times and better resource utilization, reducing unnecessary delays and adapting to varying load speeds .

Selenium offers a variety of locators to find elements on a web page: 'className' with 'driver.findElement(By.className("value"))', 'cssSelector' with 'driver.findElement(By.cssSelector("value"))', 'id' with 'driver.findElement(By.id("value"))', 'linkText' with 'driver.findElement(By.linkText("value"))', 'name' with 'driver.findElement(By.name("value"))', 'partialLinkText' with 'driver.findElement(By.partialLinkText("value"))', 'tagName' with 'driver.findElement(By.tagName("value"))', and 'xpath' with 'driver.findElement(By.xpath("value"))' .

In Selenium, you can switch frames using 'frame(WebElement element)' to select a frame by WebElement, 'frame(String nameOrId)' to select by name or ID, 'frame(int index)' for zero-based index, 'defaultContent()' to go back to the main document, and 'parentFrame()' to change focus to the parent context. For window switching, you use 'getWindowHandle()' to get the current window handle, 'getWindowHandles()' for all current window handles, and 'switchTo().window()' to switch focus between windows. Frame switching is used for within-page context, whereas window switching is for different browser windows or tabs .

The explicit wait feature in Selenium is a powerful tool that enhances web testing by handling dynamic elements effectively. It involves using 'WebDriverWait' to pause test execution until a specific condition is met, such as 'elementToBeClickable()' or 'textToBePresentInElement()'. This ensures the page elements are fully loaded and interactable before taking action, reducing the risk of encountering issues such as 'ElementNotVisibleException' or 'ElementNotInteractableException'. These waits allow tailoring wait conditions to specific cases, improving reliability and robustness in dynamic environments .

The 'presenceOfElementLocated()' expected condition in Selenium helps ensure test script stability by confirming that an element is present in the DOM of a page before any further actions are taken. This condition is particularly useful for handling cases where the action sequence might proceed faster than the DOM updates, potentially leading to missed interactions with the desired elements. By waiting for element presence, this mechanism minimizes errors such as 'NoSuchElementException', ensuring that the web page state is appropriate for the automated interactions .

The 'getWindowHandle()' method in Selenium is used to obtain the unique handle for the current window, which is essential when you need to work with multiple windows or tabs to ensure you are interacting with the correct one. 'getWindowHandles()' retrieves handles for all open windows, allowing you to iterate through them and switch focus using 'switchTo().window()'. These methods are crucial in test automation for managing scenarios where pop-ups or additional browser windows are involved .

You might also like