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
- ID
- Name
- Class Name
- Tag Name
- Link Text
- Partial Link Text
- CSS Selector
- 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");
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");
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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();
Copy
//Load a new web page in the current browser window.. driver.Url = "https://example.com"; //It will close the current window. driver.Close(); //This method will return the title of the current page. String pageTitle = driver.Title; //It will return the URL of the page currently loaded in the browser. String currentUrl = driver.Url; //Get the source of the last loaded page. String pageSource = driver.PageSource; //Quits this driver, closing every associated window. driver.Quit();
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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();
Copy
//Load a new web page in the current browser window. driver.Navigate().GoToUrl("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();
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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();
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. var size = driver.Manage().Window.Size; //This method will set the size of the current window with given parameters. driver.Manage().Window.Size = new Size(600, 800);
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
Managing Driver Timeouts
Java
C#
Python
Javascript
Kotlin
Copy
//Sets the amount of time the driver should wait when searching for an element if it is not immediately present. driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10)); //Sets the amount of time to wait for a page load to complete before throwing an error. driver.manage().timeouts().pageLoadTimeout(Duration.ofSeconds(10)); //Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. driver.manage().timeouts().scriptTimeout(Duration.ofSeconds(10));
Copy
//Sets the amount of time the driver should wait when searching for an element if it is not immediately present. driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(10); //Sets the amount of time to wait for a page load to complete before throwing an error. driver.Manage().Timeouts().PageLoad = TimeSpan.FromSeconds(10); //Sets the amount of time to wait for an asynchronous script to finish execution before throwing an error. driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(10);
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
WebDriver Wait
Explicit Wait
Java
C#
Python
Javascript
Kotlin
Copy
WebDriver driver = new ChromeDriver(); driver.get("https://www.testautomationstudio.com/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();
Copy
IWebDriver driver = new ChromeDriver(); driver.Url = "https://www.testautomationstudio.com/demo/wait/"; driver.Manage().Window.Maximize(); driver.FindElement(By.Id("wait1")).Click(); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10)); wait.Until(d =>d.FindElement(By.Id("wait1Status")).Text.Equals("Wait 1 Status")); driver.Quit();
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
Fluent Wait
Java
C#
Python
Javascript
Kotlin
Copy
WebDriver driver = new ChromeDriver(); driver.get("https://www.testautomationstudio.com/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();
Copy
IWebDriver driver = new ChromeDriver(); driver.Url = "https://www.testautomationstudio.com/demo/wait/"; driver.Manage().Window.Maximize(); driver.FindElement(By.Id("wait1")).Click(); WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15)); wait.PollingInterval = TimeSpan.FromSeconds(2); wait.IgnoreExceptionTypes(typeof(NoSuchElementException)); wait.Until(d => d.FindElement(By.Id("wait1Status")).Text.Equals("Wait 1 Status")); driver.Quit();
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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; } }
Copy
//Getting first window handle String firstWindowHandle = driver.CurrentWindowHandle; //Click on link to open second window driver.FindElement(By.Id("page2Link")).Click(); //Getting all opened window handles var allOpenWindowHandles = driver.WindowHandles; //Looping through all window handles to switch to new window handle foreach (String windowHandle in allOpenWindowHandles) { if (!windowHandle.Equals(firstWindowHandle)) { driver.SwitchTo().Window(windowHandle); break; } }
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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();
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();
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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");
Copy
//Switch to alert IAlert alert = driver.SwitchTo().Alert(); // To accept the alert dialog alert.Accept(); // To dismiss the alert dialog alert.Dismiss(); // To get alert dialog text String alertText = alert.Text; // To enter text in prompt dialog alert.SendKeys("sample");
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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();
Copy
//Find the first WebElement using the given method. IWebElement element = driver.FindElement(By.Id("some_id")); //Find all elements within the current page using the given mechanism. var 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 String text = element.Text; // Check if this element displayed bool isDisplayed = element.Displayed; // Check if this element enabled bool isEnabled = element.Enabled; // Get the tag name of this element String tagName = element.TagName; // 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();
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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();
Copy
SelectElement select = new SelectElement(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.SelectByText("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.DeselectByText("visible text"); // Returns all selected options belonging to this select tag var allSelected = select.AllSelectedOptions; // Returns the first selected option in this select tag var firstSelected = select.SelectedOption; // Returns all options belonging to this select tag var options = select.Options; // Check whether this select element support selecting multiple options bool isMultiple = select.IsMultiple;
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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);");
Copy
IJavaScriptExecutor je = (IJavaScriptExecutor)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);");
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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();
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();
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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();
Copy
//Automatically downloads and configures the ChromeDriver binary new WebDriverManager.DriverManager().SetUpDriver(new ChromeConfig()); IWebDriver driver = new ChromeDriver(); driver.Url = "https://www.testautomationstudio.com/demo/home/"; driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30); driver.Manage().Window.Maximize(); driver.Quit();
Python code coming soon
Javascript code coming soon
Kotlin code coming soon
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();
Copy
ChromeOptions options = new ChromeOptions(); //Add Options options.AddArgument("--headless"); IWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444"), options); driver.Url = "https://www.testautomationstudio.com/demo/home/"; driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromSeconds(30); driver.Manage().Window.Maximize(); driver.Quit();
Python code coming soon
Javascript code coming soon
Kotlin code coming soon