Get browser information
Get title
You can read the current page title from the browser:
driver.titleGet current URL
You can read the current URL from the browser’s address bar using:
driver.currentUrlThis is the multi-page printable view of this section. Click here to print.
The first thing you will want to do after launching a browser is to open your website. This can be achieved in a single line:
//Convenient
driver.get("https://selenium.dev")
//Longer way
driver.navigate().to("https://selenium.dev")
Pressing the browser’s back button:
driver.navigate().back() Pressing the browser’s forward button:
driver.navigate().forward()Refresh the current page:
driver.navigate().refresh()WebDriver provides an API for working with the three types of native popup messages offered by JavaScript. These popups are styled by the browser and offer limited customisation.
The simplest of these is referred to as an alert, which shows a custom message, and a single button which dismisses the alert, labelled in most browsers as OK. It can also be dismissed in most browsers by pressing the close button, but this will always do the same thing as the OK button. See an example alert.
WebDriver can get the text from the popup and accept or dismiss these alerts.
//Click the link to activate the alert
driver.FindElement(By.LinkText("See an example alert")).Click();
//Wait for the alert to be displayed and store it in a variable
IAlert alert = wait.Until(ExpectedConditions.AlertIsPresent());
//Store the alert text in a variable
string text = alert.Text;
//Press the OK button
alert.Accept();
//Click the link to activate the alert
driver.findElement(By.linkText("See an example alert")).click()
//Wait for the alert to be displayed and store it in a variable
val alert = wait.until(ExpectedConditions.alertIsPresent())
//Store the alert text in a variable
val text = alert.getText()
//Press the OK button
alert.accept()
A confirm box is similar to an alert, except the user can also choose to cancel the message. See a sample confirm.
This example also shows a different approach to storing an alert:
//Click the link to activate the alert
driver.FindElement(By.LinkText("See a sample confirm")).Click();
//Wait for the alert to be displayed
wait.Until(ExpectedConditions.AlertIsPresent());
//Store the alert in a variable
IAlert alert = driver.SwitchTo().Alert();
//Store the alert in a variable for reuse
string text = alert.Text;
//Press the Cancel button
alert.Dismiss();
//Click the link to activate the alert
driver.findElement(By.linkText("See a sample confirm")).click()
//Wait for the alert to be displayed
wait.until(ExpectedConditions.alertIsPresent())
//Store the alert in a variable
val alert = driver.switchTo().alert()
//Store the alert in a variable for reuse
val text = alert.text
//Press the Cancel button
alert.dismiss()
Prompts are similar to confirm boxes, except they also include a text input. Similar to working with form elements, you can use WebDriver’s send keys to fill in a response. This will completely replace the placeholder text. Pressing the cancel button will not submit any text. See a sample prompt.
A cookie is a small piece of data that is sent from a website and stored in your computer. Cookies are mostly used to recognise the user and load the stored information.
WebDriver API provides a way to interact with cookies with built-in methods:
It is used to add a cookie to the current browsing context. Add Cookie only accepts a set of defined serializable JSON object. Here is the link to the list of accepted JSON key values
First of all, you need to be on the domain that the cookie will be valid for. If you are trying to preset cookies before you start interacting with a site and your homepage is large / takes a while to load an alternative is to find a smaller page on the site (typically the 404 page is small, e.g. http://example.com/some404page)
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("https://example.com")
// Adds the cookie into current browser context
driver.manage().addCookie(Cookie("key", "value"))
} finally {
driver.quit()
}
}
It returns the serialized cookie data matching with the cookie name among all associated cookies.
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("https://example.com")
driver.manage().addCookie(Cookie("foo", "bar"))
// Get cookie details with named cookie 'foo'
val cookie = driver.manage().getCookieNamed("foo")
println(cookie)
} finally {
driver.quit()
}
}
It returns a ‘successful serialized cookie data’ for current browsing context. If browser is no longer available it returns error.
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("https://example.com")
driver.manage().addCookie(Cookie("test1", "cookie1"))
driver.manage().addCookie(Cookie("test2", "cookie2"))
// Get All available cookies
val cookies = driver.manage().cookies
println(cookies)
} finally {
driver.quit()
}
}
It deletes the cookie data matching with the provided cookie name.
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("https://example.com")
driver.manage().addCookie(Cookie("test1", "cookie1"))
val cookie1 = Cookie("test2", "cookie2")
driver.manage().addCookie(cookie1)
// delete a cookie with name 'test1'
driver.manage().deleteCookieNamed("test1")
// delete cookie by passing cookie object of current browsing context.
driver.manage().deleteCookie(cookie1)
} finally {
driver.quit()
}
}
It deletes all the cookies of the current browsing context.
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("https://example.com")
driver.manage().addCookie(Cookie("test1", "cookie1"))
driver.manage().addCookie(Cookie("test2", "cookie2"))
// deletes all cookies
driver.manage().deleteAllCookies()
} finally {
driver.quit()
}
}
It allows a user to instruct browsers to control whether cookies are sent along with the request initiated by third party sites. It is introduced to prevent CSRF (Cross-Site Request Forgery) attacks.
Same-Site cookie attribute accepts two parameters as instructions
When the sameSite attribute is set as Strict, the cookie will not be sent along with requests initiated by third party websites.
When you set a cookie sameSite attribute to Lax, the cookie will be sent along with the GET request initiated by third party website.
Note: As of now this feature is landed in chrome(80+version), Firefox(79+version) and works with Selenium 4 and later versions.
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SameSiteCookie {
class SameSiteCookie {
static void Main(string[] args) {
IWebDriver driver = new ChromeDriver();
try {
driver.Navigate().GoToUrl("http://www.example.com");
var cookie1Dictionary = new System.Collections.Generic.Dictionary<string, object>() {
{ "name", "test1" }, { "value", "cookie1" }, { "sameSite", "Strict" } };
var cookie1 = Cookie.FromDictionary(cookie1Dictionary);
var cookie2Dictionary = new System.Collections.Generic.Dictionary<string, object>() {
{ "name", "test2" }, { "value", "cookie2" }, { "sameSite", "Lax" } };
var cookie2 = Cookie.FromDictionary(cookie2Dictionary);
driver.Manage().Cookies.AddCookie(cookie1);
driver.Manage().Cookies.AddCookie(cookie2);
System.Console.WriteLine(cookie1.SameSite);
System.Console.WriteLine(cookie2.SameSite);
} finally {
driver.Quit();
}
}
}
}
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
begin
driver.get 'https://www.example.com'
# Adds the cookie into current browser context with sameSite 'Strict' (or) 'Lax'
driver.manage.add_cookie(name: "foo", value: "bar", same_site: "Strict")
driver.manage.add_cookie(name: "foo1", value: "bar", same_site: "Lax")
puts driver.manage.cookie_named('foo')
puts driver.manage.cookie_named('foo1')
ensure
driver.quit
end
import org.openqa.selenium.Cookie
import org.openqa.selenium.chrome.ChromeDriver
fun main() {
val driver = ChromeDriver()
try {
driver.get("http://www.example.com")
val cookie = Cookie.Builder("key", "value").sameSite("Strict").build()
val cookie1 = Cookie.Builder("key", "value").sameSite("Lax").build()
driver.manage().addCookie(cookie)
driver.manage().addCookie(cookie1)
println(cookie.getSameSite())
println(cookie1.getSameSite())
} finally {
driver.quit()
}
}
Frames are a now deprecated means of building a site layout from multiple documents on the same domain. You are unlikely to work with them unless you are working with an pre HTML5 webapp. Iframes allow the insertion of a document from an entirely different domain, and are still commonly used.
If you need to work with frames or iframes, WebDriver allows you to work with them in the same way. Consider a button within an iframe. If we inspect the element using the browser development tools, we might see the following:
<div id="modal">
<iframe id="buttonframe" name="myframe" src="https://seleniumhq.github.io">
<button>Click here</button>
</iframe>
</div>
If it was not for the iframe we would expect to click on the button using something like:
//This won't work
driver.findElement(By.tagName("button")).click();
# This Wont work
driver.find_element(By.TAG_NAME, 'button').click()
//This won't work
driver.FindElement(By.TagName("button")).Click();
# This won't work
driver.find_element(:tag_name,'button').click
// This won't work
await driver.findElement(By.css('button')).click();
//This won't work
driver.findElement(By.tagName("button")).click()
However, if there are no buttons outside of the iframe, you might instead get a no such element error. This happens because Selenium is only aware of the elements in the top level document. To interact with the button, we will need to first switch to the frame, in a similar way to how we switch windows. WebDriver offers three ways of switching to a frame. Following example code shows how we can do that, using a live web example.
Switching using a WebElement is the most flexible option. You can find the frame using your preferred selector and switch to it.
// Store the web element
const iframe = driver.findElement(By.css('#modal > iframe'));
// Switch to the frame
await driver.switchTo().frame(iframe);
// Now we can click the button
await driver.findElement(By.css('button')).click();
//Store the web element
val iframe = driver.findElement(By.cssSelector("#modal>iframe"))
//Switch to the frame
driver.switchTo().frame(iframe)
//Now we can click the button
driver.findElement(By.tagName("button")).click()
If your frame or iframe has an id or name attribute, this can be used instead. If the name or ID is not unique on the page, then the first one found will be switched to.
// Using the ID
await driver.switchTo().frame('buttonframe');
// Or using the name instead
await driver.switchTo().frame('myframe');
// Now we can click the button
await driver.findElement(By.css('button')).click();
//Using the ID
driver.switchTo().frame("buttonframe")
//Or using the name instead
driver.switchTo().frame("myframe")
//Now we can click the button
driver.findElement(By.tagName("button")).click()
It is also possible to use the index of the frame, such as can be queried using window.frames in JavaScript.
// Switches to the second frame
await driver.switchTo().frame(1);
// Switches to the second frame
driver.switchTo().frame(1)
To leave an iframe or frameset, switch back to the default content like so:
// Return to the top level
await driver.switchTo().defaultContent();
// Return to the top level
driver.switchTo().defaultContent()
Printing a webpage is a common task, whether for sharing information or maintaining archives. Selenium simplifies this process through its PrintOptions, PrintsPage, and browsingContext classes, which provide a flexible and intuitive interface for automating the printing of web pages. These classes enable you to configure printing preferences, such as page layout, margins, and scaling, ensuring that the output meets your specific requirements.
Using the getOrientation() and setOrientation() methods, you can get/set the page orientation — either PORTRAIT or LANDSCAPE.
Using the getPageRanges() and setPageRanges() methods, you can get/set the range of pages to print — e.g. “2-4”.
Using the getPageSize() and setPageSize() methods, you can get/set the paper size to print — e.g. “A0”, “A6”, “Legal”, “Tabloid”, etc.
Using the getPageMargin() and setPageMargin() methods, you can set the margin sizes of the page you wish to print — i.e. top, bottom, left, and right margins.
Using getScale() and setScale() methods, you can get/set the scale of the page you wish to print — e.g. 1.0 is 100% or default, 0.25 is 25%, etc.
Using getBackground() and setBackground() methods, you can get/set whether background colors and images appear — boolean true or false.
Using getShrinkToFit() and setShrinkToFit() methods, you can get/set whether the page will shrink-to-fit content on the page — boolean true or false.
Once you’ve configured your PrintOptions, you’re ready to print the page. To do this,
you can invoke the print function, which generates a PDF representation of the web page.
The resulting PDF can be saved to your local storage for further use or distribution.
Using PrintsPage(), the print command will return the PDF data in base64-encoded format, which can be decoded
and written to a file in your desired location, and using BrowsingContext() will return a String.
There may currently be multiple implementations depending on your language of choice. For example, with Java you
have the ability to print using either BrowingContext() or PrintsPage(). Both take PrintOptions() objects as a
parameter.
Note: BrowsingContext() is part of Selenium’s BiDi implementation. To enable BiDi see Enabling Bidi
PrintsPage()
BrowsingContext()
print_page()
WebDriver does not make the distinction between windows and tabs. If your site opens a new tab or window, Selenium will let you work with it using a window handle. Each window has a unique identifier which remains persistent in a single session. You can get the window handle of the current window by using:
driver.current_window_handledriver.window_handleawait driver.getWindowHandle();driver.windowHandleClicking a link which opens in a new window will focus the new window or tab on screen, but WebDriver will not know which window the Operating System considers active. To work with the new window you will need to switch to it. For this, we fetch all window handles, and store them in an array. The array position fills in the order the window is launched. So first position will be default browser, and so on.
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
with webdriver.Firefox() as driver:
# Open URL
driver.get("https://seleniumhq.github.io")
# Setup wait for later
wait = WebDriverWait(driver, 10)
# Store the ID of the original window
original_window = driver.current_window_handle
# Check we don't have other windows open already
assert len(driver.window_handles) == 1
# Click the link which opens in a new window
driver.find_element(By.LINK_TEXT, "new window").click()
# Wait for the new window or tab
wait.until(EC.number_of_windows_to_be(2))
# Loop through until we find a new window handle
for window_handle in driver.window_handles:
if window_handle != original_window:
driver.switch_to.window(window_handle)
break
# Wait for the new tab to finish loading content
wait.until(EC.title_is("SeleniumHQ Browser Automation"))
# Store the ID of the original window
original_window = driver.window_handle
# Check we don't have other windows open already
assert(driver.window_handles.length == 1, 'Expected one window')
# Click the link which opens in a new window
driver.find_element(link: 'new window').click
# Wait for the new window or tab
wait.until { driver.window_handles.length == 2 }
#Loop through until we find a new window handle
driver.window_handles.each do |handle|
if handle != original_window
driver.switch_to.window handle
break
end
end
#Wait for the new tab to finish loading content
wait.until { driver.title == 'Selenium documentation'}
//Store the ID of the original window
const originalWindow = await driver.getWindowHandle();
//Check we don't have other windows open already
assert((await driver.getAllWindowHandles()).length === 1);
//Click the link which opens in a new window
await driver.findElement(By.linkText('new window')).click();
//Wait for the new window or tab
await driver.wait(
async () => (await driver.getAllWindowHandles()).length === 2,
10000
);
//Loop through until we find a new window handle
const windows = await driver.getAllWindowHandles();
windows.forEach(async handle => {
if (handle !== originalWindow) {
await driver.switchTo().window(handle);
}
});
//Wait for the new tab to finish loading content
await driver.wait(until.titleIs('Selenium documentation'), 10000);
//Store the ID of the original window
val originalWindow = driver.getWindowHandle()
//Check we don't have other windows open already
assert(driver.getWindowHandles().size() === 1)
//Click the link which opens in a new window
driver.findElement(By.linkText("new window")).click()
//Wait for the new window or tab
wait.until(numberOfWindowsToBe(2))
//Loop through until we find a new window handle
for (windowHandle in driver.getWindowHandles()) {
if (!originalWindow.contentEquals(windowHandle)) {
driver.switchTo().window(windowHandle)
break
}
}
//Wait for the new tab to finish loading content
wait.until(titleIs("Selenium documentation"))
When you are finished with a window or tab and it is not the last window or tab open in your browser, you should close it and switch back to the window you were using previously. Assuming you followed the code sample in the previous section you will have the previous window handle stored in a variable. Put this together and you will get:
#Close the tab or window
driver.close()
#Switch back to the old tab or window
driver.switch_to.window(original_window)
#Close the tab or window
driver.close
#Switch back to the old tab or window
driver.switch_to.window original_window
//Close the tab or window
await driver.close();
//Switch back to the old tab or window
await driver.switchTo().window(originalWindow);
//Close the tab or window
driver.close()
//Switch back to the old tab or window
driver.switchTo().window(originalWindow)
Forgetting to switch back to another window handle after closing a window will leave WebDriver executing on the now closed page, and will trigger a No Such Window Exception. You must switch back to a valid window handle in order to continue execution.
Creates a new window (or) tab and will focus the new window or tab on screen. You don’t need to switch to work with the new window (or) tab. If you have more than two windows (or) tabs opened other than the new window, you can loop over both windows or tabs that WebDriver can see, and switch to the one which is not the original.
Note: This feature works with Selenium 4 and later versions.
# Opens a new tab and switches to new tab
driver.switch_to.new_window('tab')
# Opens a new window and switches to new window
driver.switch_to.new_window('window')
Opens a new tab and switches to new tab:
Opens a new window and switches to new window:
// Opens a new tab and switches to new tab
driver.switchTo().newWindow(WindowType.TAB)
// Opens a new window and switches to new window
driver.switchTo().newWindow(WindowType.WINDOW)
When you are finished with the browser session you should call quit, instead of close:
driver.quit()driver.quitawait driver.quit();driver.quit()Failure to call quit will leave extra background processes and ports running on your machine which could cause you problems later.
Some test frameworks offer methods and annotations which you can hook into to tear down at the end of a test.
/**
* Example using JUnit
* https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
*/
@AfterAll
public static void tearDown() {
driver.quit();
}
# unittest teardown
# https://docs.python.org/3/library/unittest.html?highlight=teardown#unittest.TestCase.tearDown
def tearDown(self):
self.driver.quit()
/*
Example using Visual Studio's UnitTesting
https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.aspx
*/
[TestCleanup]
public void TearDown()
{
driver.Quit();
}
# UnitTest Teardown
# https://www.rubydoc.info/github/test-unit/test-unit/Test/Unit/TestCase
def teardown
@driver.quit
end
/**
* Example using Mocha
* https://mochajs.org/#hooks
*/
after('Tear down', async function () {
await driver.quit();
});
/**
* Example using JUnit
* https://junit.org/junit5/docs/current/api/org/junit/jupiter/api/AfterAll.html
*/
@AfterAll
fun tearDown() {
driver.quit()
}
If not running WebDriver in a test context, you may consider using
try / finally which is offered by most languages so that an exception
will still clean up the WebDriver session.
try {
//WebDriver code here...
} finally {
driver.quit();
}
try:
#WebDriver code here...
finally:
driver.quit()
try {
//WebDriver code here...
} finally {
driver.Quit();
}
begin
#WebDriver code here...
ensure
driver.quit
end
try {
//WebDriver code here...
} finally {
await driver.quit();
}
try {
//WebDriver code here...
} finally {
driver.quit()
}
Python’s WebDriver now supports the python context manager,
which when using the with keyword can automatically quit the driver at
the end of execution.
with webdriver.Firefox() as driver:
# WebDriver code here...
# WebDriver will automatically quit after indentation
Screen resolution can impact how your web application renders, so WebDriver provides mechanisms for moving and resizing the browser window.
Fetches the size of the browser window in pixels.
//Access each dimension individually
int width = driver.manage().window().getSize().getWidth();
int height = driver.manage().window().getSize().getHeight();
//Or store the dimensions and query them later
Dimension size = driver.manage().window().getSize();
int width1 = size.getWidth();
int height1 = size.getHeight();
# Access each dimension individually
width = driver.get_window_size().get("width")
height = driver.get_window_size().get("height")
# Or store the dimensions and query them later
size = driver.get_window_size()
width1 = size.get("width")
height1 = size.get("height")
//Access each dimension individually
int width = driver.Manage().Window.Size.Width;
int height = driver.Manage().Window.Size.Height;
//Or store the dimensions and query them later
System.Drawing.Size size = driver.Manage().Window.Size;
int width1 = size.Width;
int height1 = size.Height;
# Access each dimension individually
width = driver.manage.window.size.width
height = driver.manage.window.size.height
# Or store the dimensions and query them later
size = driver.manage.window.size
width1 = size.width
height1 = size.height
//Access each dimension individually
val width = driver.manage().window().size.width
val height = driver.manage().window().size.height
//Or store the dimensions and query them later
val size = driver.manage().window().size
val width1 = size.width
val height1 = size.height
Restores the window and sets the window size.
driver.manage().window().setSize(new Dimension(1024, 768));driver.set_window_size(1024, 768)driver.Manage().Window.Size = new Size(1024, 768);driver.manage.window.resize_to(1024,768)await driver.manage().window().setRect({ width: 1024, height: 768 });driver.manage().window().size = Dimension(1024, 768)Fetches the coordinates of the top left coordinate of the browser window.
// Access each dimension individually
int x = driver.manage().window().getPosition().getX();
int y = driver.manage().window().getPosition().getY();
// Or store the dimensions and query them later
Point position = driver.manage().window().getPosition();
int x1 = position.getX();
int y1 = position.getY();
# Access each dimension individually
x = driver.get_window_position().get('x')
y = driver.get_window_position().get('y')
# Or store the dimensions and query them later
position = driver.get_window_position()
x1 = position.get('x')
y1 = position.get('y')
//Access each dimension individually
int x = driver.Manage().Window.Position.X;
int y = driver.Manage().Window.Position.Y;
//Or store the dimensions and query them later
Point position = driver.Manage().Window.Position;
int x1 = position.X;
int y1 = position.Y;
#Access each dimension individually
x = driver.manage.window.position.x
y = driver.manage.window.position.y
# Or store the dimensions and query them later
rect = driver.manage.window.rect
x1 = rect.x
y1 = rect.y
// Access each dimension individually
val x = driver.manage().window().position.x
val y = driver.manage().window().position.y
// Or store the dimensions and query them later
val position = driver.manage().window().position
val x1 = position.x
val y1 = position.y
Moves the window to the chosen position.
// Move the window to the top left of the primary monitor
driver.manage().window().setPosition(new Point(0, 0));
# Move the window to the top left of the primary monitor
driver.set_window_position(0, 0)
// Move the window to the top left of the primary monitor
driver.Manage().Window.Position = new Point(0, 0);
driver.manage.window.move_to(0,0)
// Move the window to the top left of the primary monitor
await driver.manage().window().setRect({ x: 0, y: 0 });
// Move the window to the top left of the primary monitor
driver.manage().window().position = Point(0,0)
Enlarges the window. For most operating systems, the window will fill the screen, without blocking the operating system’s own menus and toolbars.
driver.manage().window().maximize();driver.maximize_window()driver.Manage().Window.Maximize();driver.manage.window.maximizeawait driver.manage().window().maximize();driver.manage().window().maximize()Minimizes the window of current browsing context. The exact behavior of this command is specific to individual window managers.
Minimize Window typically hides the window in the system tray.
Note: This feature works with Selenium 4 and later versions.
driver.manage().window().minimize();driver.minimize_window()driver.Manage().Window.Minimize();driver.manage.window.minimizeawait driver.manage().window().minimize();driver.manage().window().minimize()Fills the entire screen, similar to pressing F11 in most browsers.
driver.manage().window().fullscreen();driver.fullscreen_window()driver.Manage().Window.FullScreen();driver.manage.window.full_screenawait driver.manage().window().fullscreen();driver.manage().window().fullscreen()Used to capture screenshot for current browsing context. The WebDriver endpoint screenshot returns screenshot which is encoded in Base64 format.
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.*;
import org.openqa.selenium.*;
public class SeleniumTakeScreenshot {
public static void main(String args[]) throws IOException {
WebDriver driver = new ChromeDriver();
driver.get("http://www.example.com");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("./image.png"));
driver.quit();
}
}
from selenium import webdriver
driver = webdriver.Chrome()
driver.get("http://www.example.com")
# Returns and base64 encoded string into image
driver.save_screenshot('./image.png')
driver.quit() using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
var driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://www.example.com");
Screenshot screenshot = (driver as ITakesScreenshot).GetScreenshot();
screenshot.SaveAsFile("screenshot.png", ScreenshotImageFormat.Png); // Format values are Bmp, Gif, Jpeg, Png, Tiff
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
begin
driver.get 'https://example.com/'
# Takes and Stores the screenshot in specified path
driver.save_screenshot('./image.png')
end
import com.oracle.tools.packager.IOUtils.copyFile
import org.openqa.selenium.*
import org.openqa.selenium.chrome.ChromeDriver
import java.io.File
fun main(){
val driver = ChromeDriver()
driver.get("https://www.example.com")
val scrFile = (driver as TakesScreenshot).getScreenshotAs<File>(OutputType.FILE)
copyFile(scrFile, File("./image.png"))
driver.quit()
}
Used to capture screenshot of an element for current browsing context. The WebDriver endpoint screenshot returns screenshot which is encoded in Base64 format.
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import java.io.File;
import java.io.IOException;
public class SeleniumelementTakeScreenshot {
public static void main(String args[]) throws IOException {
WebDriver driver = new ChromeDriver();
driver.get("https://www.example.com");
WebElement element = driver.findElement(By.cssSelector("h1"));
File scrFile = element.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("./image.png"));
driver.quit();
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
driver = webdriver.Chrome()
driver.get("http://www.example.com")
ele = driver.find_element(By.CSS_SELECTOR, 'h1')
# Returns and base64 encoded string into image
ele.screenshot('./image.png')
driver.quit()
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
// Webdriver
var driver = new ChromeDriver();
driver.Navigate().GoToUrl("http://www.example.com");
// Fetch element using FindElement
var webElement = driver.FindElement(By.CssSelector("h1"));
// Screenshot for the element
var elementScreenshot = (webElement as ITakesScreenshot).GetScreenshot();
elementScreenshot.SaveAsFile("screenshot_of_element.png");
# Works with Selenium4-alpha7 Ruby bindings and above
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :chrome
begin
driver.get 'https://example.com/'
ele = driver.find_element(:css, 'h1')
# Takes and Stores the element screenshot in specified path
ele.save_screenshot('./image.jpg')
end
import org.apache.commons.io.FileUtils
import org.openqa.selenium.chrome.ChromeDriver
import org.openqa.selenium.*
import java.io.File
fun main() {
val driver = ChromeDriver()
driver.get("https://www.example.com")
val element = driver.findElement(By.cssSelector("h1"))
val scrFile: File = element.getScreenshotAs(OutputType.FILE)
FileUtils.copyFile(scrFile, File("./image.png"))
driver.quit()
}
Executes JavaScript code snippet in the current context of a selected frame or window.
//Creating the JavascriptExecutor interface object by Type casting
JavascriptExecutor js = (JavascriptExecutor)driver;
//Button Element
WebElement button =driver.findElement(By.name("btnLogin"));
//Executing JavaScript to click on element
js.executeScript("arguments[0].click();", button);
//Get return value from script
String text = (String) js.executeScript("return arguments[0].innerText", button);
//Executing JavaScript directly
js.executeScript("console.log('hello world')");
# Stores the header element
header = driver.find_element(By.CSS_SELECTOR, "h1")
# Executing JavaScript to capture innerText of header element
driver.execute_script('return arguments[0].innerText', header)
//creating Chromedriver instance
IWebDriver driver = new ChromeDriver();
//Creating the JavascriptExecutor interface object by Type casting
IJavaScriptExecutor js = (IJavaScriptExecutor) driver;
//Button Element
IWebElement button = driver.FindElement(By.Name("btnLogin"));
//Executing JavaScript to click on element
js.ExecuteScript("arguments[0].click();", button);
//Get return value from script
String text = (String)js.ExecuteScript("return arguments[0].innerText", button);
//Executing JavaScript directly
js.ExecuteScript("console.log('hello world')");
# Stores the header element
header = driver.find_element(css: 'h1')
# Get return value from script
result = driver.execute_script("return arguments[0].innerText", header)
# Executing JavaScript directly
driver.execute_script("alert('hello world')")
// Stores the header element
val header = driver.findElement(By.cssSelector("h1"))
// Get return value from script
val result = driver.executeScript("return arguments[0].innerText", header)
// Executing JavaScript directly
driver.executeScript("alert('hello world')")
Prints the current page within the browser.
Note: This requires Chromium Browsers to be in headless mode
import org.openqa.selenium.print.PrintOptions;
driver.get("https://www.selenium.dev");
printer = (PrintsPage) driver;
PrintOptions printOptions = new PrintOptions();
printOptions.setPageRanges("1-2");
Pdf pdf = printer.print(printOptions);
String content = pdf.getContent();
from selenium.webdriver.common.print_page_options import PrintOptions
print_options = PrintOptions()
print_options.page_ranges = ['1-2']
driver.get("printPage.html")
base64code = driver.print_page(print_options)
// code sample not available please raise a PR
driver.navigate_to 'https://www.selenium.dev'
base64encodedContent = driver.print_page(orientation: 'landscape')
driver.get("https://www.selenium.dev")
val printer = driver as PrintsPage
val printOptions = PrintOptions()
printOptions.setPageRanges("1-2")
val pdf: Pdf = printer.print(printOptions)
val content = pdf.content
Web applications can enable a public key-based authentication mechanism known as Web Authentication to authenticate users in a passwordless manner. Web Authentication defines APIs that allows a user to create a public-key credential and register it with an authenticator. An authenticator can be a hardware device or a software entity that stores user’s public-key credentials and retrieves them on request.
As the name suggests, Virtual Authenticator emulates such authenticators for testing.
A Virtual Authenticatior has a set of properties. These properties are mapped as VirtualAuthenticatorOptions in the Selenium bindings.
It creates a new virtual authenticator with the provided properties.
Removes the previously added virtual authenticator.
Creates a resident (stateful) credential with the given required credential parameters.
Creates a resident (stateless) credential with the given required credential parameters.
Registers the credential with the authenticator.
Returns the list of credentials owned by the authenticator.
Removes a credential from the authenticator based on the passed credential id.
Removes all the credentials from the authenticator.
Sets whether the authenticator will simulate success or fail on user verification.
Learn more or view the full list of sponsors.