Selenium
Course Index
Index

Selenium WebDriver Cheat Sheet

What is Selenium

Selenium is an open-source, cross-platform framework that allows you to automate web browsers. It provides a way to interact with web elements, perform actions, and validate the behavior of web applications, just like a real user would. Selenium supports various programming languages, including Java, Python, C#, and more, making it versatile and accessible to a broad range of developers and testers.

Components of Selenium

Selenium is composed of several key components:

  • Selenium WebDriver: The core component for automating web browsers. It provides a programming interface for interacting with web elements and browsers.
  • Selenium IDE: A record-and-playback tool for creating simple automation scripts without coding. Useful for beginners and quick test case creation.
  • Selenium Grid: Allows you to distribute test execution across multiple machines, browsers, and platforms simultaneously. Ideal for running tests in parallel to save time.

Locators


  1. ID
  2. Name
  3. Class Name
  4. Tag Name
  5. Link Text
  6. Partial Link Text
  7. CSS Selector
  8. XPath
Java
C#
Python
Javascript
Kotlin
Copy
// Find element by id
By.id("element_id");

// Find element name
By.name("name");

// Find element by class name
By.className("class_name");

// Find element tag name
By.tagName("tag_name");

// Find element link text
By.linkText("link_text");

// Find element by partial link text
By.partialLinkText("partial_link_text");

// Find element by css selector
By.cssSelector("#css_selector");

// Find element by xpath
By.xpath("//xpath");

WebDriver Methods



Java
C#
Python
Javascript
Kotlin
Copy
//Load a new web page in the current browser window..
driver.get("https://example.com");

//It will close the current window.
driver.close();

//This method will return the title of the current page.
driver.getTitle();

//It will return the URL of the page currently loaded in the browser.
driver.getCurrentUrl();

//Get the source of the last loaded page.
driver.getPageSource();

//Quits this driver, closing every associated window.
driver.quit();

Navigation Methods



Java
C#
Python
Javascript
Kotlin
Copy
//Load a new web page in the current browser window.
driver.navigate().to("http://www.example2.com");

// Move back a single "item" in the browser's history.
driver.navigate().back();

// Move a single "item" forward in the browser's history.
driver.navigate().forward();

// Refresh the current page
driver.navigate().refresh();

Managing current window



Java
C#
Python
Javascript
Kotlin
Copy
//Fullscreen the current window if it is not already fullscreen
driver.manage().window().fullscreen();

// Maximizes the current window if it is not already maximized
driver.manage().window().maximize();

// Minimizes the current window if it is not already minimized
driver.manage().window().minimize();

//This method will return the size of the current window.
driver.manage().window().getSize();

//This method will set the size of the current window with given parameters.
driver.manage().window().setSize(new Dimension(500, 500));

Managing Driver Timeouts



Java
C#
Python
Javascript
Kotlin
Copy
//Sets the wait when searching for an element if it is not immediately present.
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));

//Sets the wait for a page load to complete before throwing an error.
driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10));

//Sets the wait for an asynchronous script to finish execution before throwing an error.
driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(10));

WebDriver Wait



Explicit Wait



Java
C#
Python
Javascript
Kotlin
Copy
WebDriver driver = new ChromeDriver();
driver.get("http://localhost:8080/demo/wait/");
driver.manage().window().maximize();
driver.findElement(By.id("wait1")).click();
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("Elem1StatusA")));
driver.quit();

Fluent Wait



Java
C#
Python
Javascript
Kotlin
Copy
WebDriver driver = new ChromeDriver();
driver.get("http://localhost:8080/demo/wait/");
driver.manage().window().maximize();

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

FluentWait<WebDriver> wait = new FluentWait<>(driver);
wait.withTimeout(Duration.ofSeconds(10));
wait.pollingEvery(Duration.ofMillis(500));
wait.ignoring(NoSuchElementException.class);

wait.until(d-> d.findElement(By.id("Elem1StatusA")).isDisplayed());

driver.quit();

Window Handles



Java
C#
Python
Javascript
Kotlin
Copy
//Getting first window handle
String firstWindowHandle = driver.getWindowHandle();
//Click on link to open second window
driver.findElement(By.id("page2Link")).click();
//Getting all opened window handles
Set<String> allOpenWindowHandles = driver.getWindowHandles();
//Looping through all window handles to switch to new window handle
for (String windowHandle : allOpenWindowHandles)
{
	if(!windowHandle.equals(firstWindowHandle))
	{
		driver.switchTo().window(windowHandle);
		break;
	}
}

Frames



Java
C#
Python
Javascript
Kotlin
Copy
// Switch to the frame
driver.switchTo().frame(frame1);
// Switch focus to the parent context.
driver.switchTo().parentFrame();
// Switch to the main document from frame
driver.switchTo().defaultContent();

Alert



Java
C#
Python
Javascript
Kotlin
Copy
//Switch to alert
Alert alert = driver.switchTo().alert();
// To accept the alert dialog
alert.accept();
// To dismiss the alert dialog
alert.dismiss();
// To get alert dialog text
alert.getText();
// To enter text in prompt dialog
alert.sendKeys("sample");

WebElement Methods



Java
C#
Python
Javascript
Kotlin
Copy
//Find the first WebElement using the given method.
WebElement element = driver.findElement(By.id("some_id"));
//Find all elements within the current page using the given mechanism. 
List<WebElement> elements = driver.findElements(By.tagName("some_tag"));
// To type into an element, which may set its value
element.sendKeys("some text");
// Get the visible text of this element
element.getText();
// Check if this element displayed
element.isDisplayed();
// Check if this element enabled
element.isEnabled();
// Get the tag name of this element
element.getTagName();
// Click this element
element.click();
// It will submit the form
element.submit();
// Get the value of the given attribute
element.getAttribute("value");
// Get the value of a given CSS property
element.getCssValue("float");
// Find the first WebElement within element
element.findElement(By.id("someId"));
// Find WebElements within element
element.findElements(By.className("items"));
// It will reset element value
element.clear();

Select Methods



Java
C#
Python
Javascript
Kotlin
Copy
Select select = new Select(element);
// Select the option at the given index.
select.selectByIndex(1);
// Select all options that have a value matching the argument.
select.selectByValue("some value");
// Select all options that display text matching the argument.
select.selectByVisibleText("Visible text");
// Clear all selected entries.
select.deselectAll();
// Deselect the option at the given index.
select.deselectByIndex(1);
// Deselect all options that have a value matching the argument.
select.deselectByValue("some value");
// Deselect all options that display text matching the argument.
select.deselectByVisibleText("visible text");
// Returns all selected options belonging to this select tag
select.getAllSelectedOptions();
// Returns the first selected option in this select tag
select.getFirstSelectedOption();
// Returns all options belonging to this select tag
select.getOptions();
// Check whether this select element support selecting multiple options
select.isMultiple();

JavaScript Executor Methods



Java
C#
Python
Javascript
Kotlin
Copy
JavascriptExecutor je = (JavascriptExecutor) driver;
// Executes JavaScript in the context of the currently selected frame or window.
je.executeScript("window.scrollBy(10,500)");
//Execute an asynchronous piece of JavaScript in the context of the currently selected frame or window.
je.executeAsyncScript("window.setTimeout(arguments[arguments.length - 1], 2000);");

Actions



Java
C#
Python
Javascript
Kotlin
Copy
// For emulating complex user gestures and keyboard or Mouse actions
Actions actions = new Actions(driver);
// Drang and drop
actions.dragAndDrop(sourceElement, destinationElement);
// Clicks at the current mouse location.
actions.click();
// Clicks (without releasing) at the current mouse location
actions.clickAndHold();
// Performs a context-click at the current mouse location.
actions.contextClick();
// Performs a double-click at the current mouse location.
actions.doubleClick();
// Performs a modifier key press.
actions.keyDown(Keys.ENTER);
// Moves the mouse to the middle of the element.
actions.moveToElement(destinationElement);
// Releases the depressed left mouse button at the current mouse location.
actions.release();
// Sends keys to the active element.
actions.sendKeys();

WebDriver Manager



Java
C#
Python
Javascript
Kotlin
Copy
// Library to import
// import io.github.bonigarcia.wdm.WebDriverManager;

//Automatically downloads and configures the ChromeDriver binary
WebDriverManager.chromedriver().setup();
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
driver.quit();

Selenium Server (Grid)



Following are the command to configure the selenium Server.

Standalone

java -jar selenium-server.jar standalone

Hub and Node

java -jar selenium-server.jar hub java -jar selenium-server.jar node java -jar selenium-server.jar node --hub http://:4444

Example code to run test on Selenium Server


Java
C#
Python
Javascript
Kotlin
Copy
ChromeOptions options = new ChromeOptions();
//Add capability
//options.setCapability("");
WebDriver driver = new RemoteWebDriver(new URL("http://localhost:4444"), options);
driver.get("https://www.testautomationstudio.com/demo/home/");

driver.quit();