### Start Browser in Java Source: https://www.selenium.dev/documentation/legacy/selenium_1 Calls setUp with the base URL and Firefox browser. This is part of a test setup that initializes the browser instance. ```java setUp("http://www.google.com/", "*firefox"); ``` -------------------------------- ### Get session map setup help with info sessionmap Source: https://www.selenium.dev/documentation/grid/configuration/help Run this command to get setup steps for different session storage options like Redis and JDBC - SQL supported databases. ```bash java -jar selenium-server-.jar info sessionmap ``` -------------------------------- ### Python PrintOptions Scale Example Source: https://www.selenium.dev/documentation/webdriver/interactions/print_page Partial Python example showing how to set the scale factor for printing. The implementation is incomplete (missing driver setup and print call). ```python driver.get("https://www.selenium.dev/") print_options = PrintOptions() print_options.scale = 0.5 ## 0.1 to 2.0 current_scale = print_options.scale ``` -------------------------------- ### Full Java example - FirstScript.java Source: https://www.selenium.dev/documentation/about/style The complete Java example file FirstScript.java, which includes starting the driver, navigating to a page, and quitting. This is the full code shown in the documentation. ```java package dev.selenium.getting_started; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.time.Duration; public class FirstScript { public static void main(String[] args) { WebDriver driver = new ChromeDriver(); driver.get("https://www.selenium.dev/selenium/web/web-form.html"); driver.getTitle(); driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500)); WebElement textBox = driver.findElement(By.name("my-text")); WebElement submitButton = driver.findElement(By.cssSelector("button")); textBox.sendKeys("Selenium"); submitButton.click(); WebElement message = driver.findElement(By.id("message")); message.getText(); driver.quit(); } } ``` -------------------------------- ### Python: Complete test_service.py example Source: https://www.selenium.dev/documentation/webdriver/drivers/service Full Python test module showing how to create a basic service, set driver location, and set a custom port. Includes a helper function to get default Chrome options. ```python from selenium import webdriver def test_basic_service(): service = webdriver.ChromeService() driver = webdriver.Chrome(service=service) driver.quit() def test_driver_location(chromedriver_bin, chrome_bin): options = get_default_chrome_options() options.binary_location = chrome_bin service = webdriver.ChromeService(executable_path=chromedriver_bin) driver = webdriver.Chrome(service=service, options=options) driver.quit() def test_driver_port(): service = webdriver.ChromeService(port=1234) driver = webdriver.Chrome(service=service) driver.quit() def get_default_chrome_options(): options = webdriver.ChromeOptions() options.add_argument("--no-sandbox") return options ``` -------------------------------- ### Start Firefox with an extension using FirefoxProfile Source: https://www.selenium.dev/documentation/legacy/selenium_2/faq To start Firefox with an extension installed, create a FirefoxProfile, add the extension, and pass the profile to the FirefoxDriver constructor. ```java FirefoxProfile profile = new FirefoxProfile() profile.addExtension(....); WebDriver driver = new FirefoxDriver(profile); ``` -------------------------------- ### Ruby: Full usage with and without Selenium Manager Source: https://www.selenium.dev/documentation/selenium_manager Complete Ruby example showing both the manual driver setup and the Selenium Manager approach. The setup_with_selenium_manager method lets Selenium Manager handle the driver automatically. ```ruby # frozen_string_literal: true require 'selenium-webdriver' def setup_without_selenium_manager service = Selenium::WebDriver::Chrome::Service.new(path: '/path/to/chromedriver') driver = Selenium::WebDriver.for(:chrome, service: service) driver.get('https://www.selenium.dev/documentation/selenium_manager/') driver.quit end def setup_with_selenium_manager driver = Selenium::WebDriver.for(:chrome) # Selenium Manager handles the driver automatically driver.get('https://www.selenium.dev/documentation/selenium_manager/') driver.quit end ``` -------------------------------- ### Get tracing setup help with info tracing Source: https://www.selenium.dev/documentation/grid/configuration/help Run this command to get instructions for exporting traces and visualizing them via Jaeger. Tracing is enabled by default. ```bash java -jar selenium-server-.jar info tracing ``` -------------------------------- ### Start Browser in Php Source: https://www.selenium.dev/documentation/legacy/selenium_1 Sets the browser and browser URL for the test. This is typically done in a setup method before running tests. ```php $this->setBrowser("*firefox"); $this->setBrowserUrl("http://www.google.com/"); ``` -------------------------------- ### Complete Java example for windows and tabs Source: https://www.selenium.dev/documentation/webdriver/interactions/windows Full Java test class demonstrating getting window handles, switching between windows, closing windows, and opening new tabs and windows using WindowType.TAB and WindowType.WINDOW. ```java package dev.selenium.interactions; import org.openqa.selenium.*; import org.openqa.selenium.chrome.ChromeDriver; import java.time.Duration; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; public class WindowsTest { @Test public void windowsExampleCode() { WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500)); // Navigate to Url driver.get("https://www.selenium.dev/selenium/web/window_switching_tests/page_with_frame.html"); //fetch handle of this String currHandle=driver.getWindowHandle(); assertNotNull(currHandle); //click on link to open a new window driver.findElement(By.linkText("Open new window")).click(); //fetch handles of all windows, there will be two, [0]- default, [1] - new window Object[] windowHandles=driver.getWindowHandles().toArray(); driver.switchTo().window((String) windowHandles[1]); //assert on title of new window String title=driver.getTitle(); assertEquals("Simple Page",title); //closing current window driver.close(); //Switch back to the old tab or window driver.switchTo().window((String) windowHandles[0]); //Opens a new tab and switches to new tab driver.switchTo().newWindow(WindowType.TAB); assertEquals("",driver.getTitle()); //Opens a new window and switches to new window driver.switchTo().newWindow(WindowType.WINDOW); assertEquals("",driver.getTitle()); //quitting driver driver.quit(); //close all windows } } ``` -------------------------------- ### Python: Manual driver setup without Selenium Manager Source: https://www.selenium.dev/documentation/selenium_manager Shows the old way of creating a Chrome service with an explicit executable path. This is the 'Previously' example for Python. ```python def setup_without_selenium_manager(): chrome_service = Service(executable_path='path/to/chrome.exe') driver = webdriver.Chrome(chrome_service) return driver ``` -------------------------------- ### Java: Use -k command switch with InternetExplorerOptions Source: https://www.selenium.dev/documentation/webdriver/browsers/internet_explorer Sets the -k command switch to launch IE in kiosk mode. Requires forceCreateProcessApi to be enabled. The example creates an InternetExplorerOptions, adds the switch, and starts the driver. ```java import org.openqa.selenium.Capabilities; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.ie.InternetExplorerOptions; public class ieTest { public static void main(String[] args) { InternetExplorerOptions options = new InternetExplorerOptions(); options.useCreateProcessApiToLaunchIe(); options.addCommandSwitches("-k"); InternetExplorerDriver driver = new InternetExplorerDriver(options); try { driver.get("https://google.com/ncr"); Capabilities caps = driver.getCapabilities(); System.out.println(caps); } finally { driver.quit(); } } } ``` -------------------------------- ### Navigate to Java examples directory Source: https://www.selenium.dev/documentation/webdriver/getting_started/first_script Change into the directory containing the Selenium Java examples after cloning the repository. ```bash cd seleniumhq.github.io/examples/java ``` -------------------------------- ### Install JavaScript dependencies with npm Source: https://www.selenium.dev/documentation/webdriver/getting_started/first_script Installs the required Node.js packages using npm. Run this after navigating to the JavaScript examples directory. ```bash npm install ``` -------------------------------- ### Start the driver - Java code snippet Source: https://www.selenium.dev/documentation/about/style This is the Java code snippet for starting the driver, as shown in the tab. It is part of the FirstScript.java example. ```java WebDriver driver = new ChromeDriver(); ``` -------------------------------- ### Start custom Node as regular jar with --ext and --node-implementation Source: https://www.selenium.dev/documentation/grid/advanced_features/customize_node Starts a custom Node packaged as a regular jar. The --ext flag adds the custom jar to the classpath, and --node-implementation specifies the fully qualified class name of the custom Node class. ```bash java -jar selenium-server-4.6.0.jar \ --ext custom_node-1.0-SNAPSHOT.jar node \ --node-implementation org.seleniumhq.samples.DecoratedLoggingNode ``` -------------------------------- ### Kotlin Internet Explorer Options Example Source: https://www.selenium.dev/documentation/webdriver/browsers/internet_explorer Kotlin example using InternetExplorerOptions to set command switches and force create process API, then launch InternetExplorerDriver and print capabilities. ```kotlin import org.openqa.selenium.Capabilities import org.openqa.selenium.ie.InternetExplorerDriver import org.openqa.selenium.ie.InternetExplorerOptions fun main() { val options = InternetExplorerOptions() options.useCreateProcessApiToLaunchIe() options.addCommandSwitches("-k") val driver = InternetExplorerDriver(options) try { driver.get("https://google.com/ncr") val caps = driver.getCapabilities() println(caps) } finally { driver.quit() } } ``` -------------------------------- ### Python: Setting Log Level and Creating Service Source: https://www.selenium.dev/documentation/webdriver/browsers/internet_explorer Python example showing how to set the log level to WARN and create an Ie service with a log file. ```python service = webdriver.IeService(log_output=log_path, log_level="WARN") driver = webdriver.Ie(service=service) ``` -------------------------------- ### Java: Get CSS Value Example Source: https://www.selenium.dev/documentation/webdriver/elements/information Java example that navigates to a color page and retrieves the computed background-color CSS value of an element using getCssValue. ```Java // Navigate to Url driver.get("https://www.selenium.dev/selenium/web/colorPage.html") // Retrieves the computed style property 'color' of linktext val cssValue = driver.findElement(By.id("namedColor")).getCssValue("background-color") ``` -------------------------------- ### Navigate to the JavaScript examples directory Source: https://www.selenium.dev/documentation/webdriver/getting_started/first_script Changes the current directory to the JavaScript examples folder within the cloned repository. ```bash cd seleniumhq.github.io/examples/javascript ``` -------------------------------- ### Run Hugo server for live preview Source: https://www.selenium.dev/documentation/about/contributing Navigate to the website_and_docs directory and start the Hugo server to preview changes. ```bash % cd website_and_docs % hugo server ``` -------------------------------- ### Java scale example Source: https://www.selenium.dev/documentation/webdriver/interactions/print_page Java code showing how to set and get the scale of the page to print using PrintOptions.setScale() and getScale(). The example sets scale to 0.50 (50%). ```java { driver.get("https://www.selenium.dev/"); PrintOptions printOptions = new PrintOptions(); printOptions.setScale(.50); double current_scale = printOptions.getScale(); ``` -------------------------------- ### C#: Complete ServiceTest.cs example Source: https://www.selenium.dev/documentation/webdriver/drivers/service Full C# test class showing how to create a default service, set driver location, and set a custom port. Includes helper methods to find driver and browser paths using DriverFinder. ```csharp using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; using SeleniumDocs.TestSupport; namespace SeleniumDocs.Drivers { [TestClass] public class ServiceTest : BaseTest { [TestMethod] public void BasicService() { var service = ChromeDriverService.CreateDefaultService(); driver = new ChromeDriver(service); } [TestMethodCustom] [EnabledOnOs("OSX")] public async System.Threading.Tasks.Task DriverLocation() { var options = GetLatestChromeOptions(); var service = ChromeDriverService.CreateDefaultService(await GetDriverLocationAsync(options)); driver = new ChromeDriver(service, options); } [TestMethod] public void DriverPort() { var service = ChromeDriverService.CreateDefaultService(); service.Port = 1234; driver = new ChromeDriver(service); } private static async System.Threading.Tasks.Task GetDriverLocationAsync(ChromeOptions options) { return await new DriverFinder(options).GetDriverPathAsync(); } private static ChromeOptions GetLatestChromeOptions() { return new ChromeOptions { BrowserVersion = "stable" }; } } } ``` -------------------------------- ### Navigate to Python examples directory Source: https://www.selenium.dev/documentation/webdriver/getting_started/using_selenium Changes the current directory to the Python examples folder within the cloned repository. ```bash cd seleniumhq.github.io/examples/python ``` -------------------------------- ### Navigate to .NET examples directory Source: https://www.selenium.dev/documentation/webdriver/getting_started/using_selenium Changes the current directory to the SeleniumDocs subfolder within the .NET examples directory. ```bash cd seleniumhq.github.io/examples/dotnet/SeleniumDocs ``` -------------------------------- ### Java PrintOptions setShrinkToFit example Source: https://www.selenium.dev/documentation/webdriver/interactions/print_page Java code showing how to set and get the shrink-to-fit option using setShrinkToFit() and getShrinkToFit(). The example sets shrink-to-fit to true and then retrieves the current value. ```java driver.get("https://www.selenium.dev/"); PrintOptions printOptions = new PrintOptions(); printOptions.setShrinkToFit(true); boolean current_shrink_to_fit = printOptions.getShrinkToFit(); ``` -------------------------------- ### Java: Get Active Element Source: https://www.selenium.dev/documentation/webdriver/elements/finders Finds the active element after sending keys to an input field. The example uses driver.switchTo().activeElement() to retrieve the focused element and get its 'name' attribute. ```java driver.findElement(By.cssSelector("#fname")).sendKeys("webElement"); String attr = driver.switchTo().activeElement().getAttribute("name"); ``` -------------------------------- ### C#: Internet Explorer options example Source: https://www.selenium.dev/documentation/webdriver/browsers/internet_explorer This C# example configures InternetExplorerOptions to force the create process API and set browser command-line arguments, then navigates to google.com/ncr. ```csharp using System; using OpenQA.Selenium; using OpenQA.Selenium.IE; namespace ieTest { class Program { static void Main(string[] args) { InternetExplorerOptions options = new InternetExplorerOptions(); options.ForceCreateProcessApi = true; options.BrowserCommandLineArguments = "-k"; IWebDriver driver = new InternetExplorerDriver(options); driver.Url = "https://google.com/ncr"; } } } ``` -------------------------------- ### Get All Cookies (Java) Source: https://www.selenium.dev/documentation/webdriver/interactions/cookies Adds two cookies to the current browser context, then retrieves all cookies using driver.manage().getCookies(). The example also shows getting a named cookie 'foo' and asserting its value. ```java // Get cookie details with named cookie 'foo' Cookie cookie = driver.manage().getCookieNamed("foo"); Assertions.assertEquals(cookie.getValue(), "bar"); } @Test public void getAllCookies() { driver.get("https://www.selenium.dev/selenium/web/blank.html"); // Add cookies into current browser context driver.manage().addCookie(new Cookie("test1", "cookie1")); driver.manage().addCookie(new Cookie("test2", "cookie2")); // Get cookies Set cookies = driver.manage().getCookies(); for (Cookie cookie : cookies) { ``` -------------------------------- ### Navigate to Ruby examples directory Source: https://www.selenium.dev/documentation/webdriver/getting_started/using_selenium Changes the current directory to the Ruby examples directory. ```bash cd seleniumhq.github.io/examples/ruby ``` -------------------------------- ### Python: Use -private argument with IeOptions Source: https://www.selenium.dev/documentation/webdriver/browsers/internet_explorer Sets the -private argument to start IE in private browsing mode. Requires forceCreateProcessApi to be enabled. The example creates an IeOptions, adds the argument, and starts the driver. ```python options = webdriver.IeOptions() options.add_argument("-private") driver = webdriver.Ie(options=options) ``` -------------------------------- ### Ruby Selenium RC Test Example Source: https://www.selenium.dev/documentation/legacy/selenium_1 Example of a Ruby test using the Selenium::Client::Driver. It sets up a test case, starts the browser, performs a search, and verifies results. The test uses the 'selenium/client' and 'test/unit' libraries. ```Ruby require "selenium/client" require "test/unit" class NewTest < Test::Unit::TestCase def setup @verification_errors = [] if $selenium @selenium = $selenium else @selenium = Selenium::Client::Driver.new("localhost", 4444, "*firefox", "http://www.google.com/", 60); @selenium.start end @selenium.set_context("test_new") end def teardown @selenium.stop unless $selenium assert_equal [], @verification_errors end def test_new @selenium.open "/" @selenium.type "q", "selenium rc" @selenium.click "btnG" @selenium.wait_for_page_to_load "30000" assert @selenium.is_text_present("Results * for selenium rc") end end ``` -------------------------------- ### Kotlin: Launch IE with create process API Source: https://www.selenium.dev/documentation/webdriver/browsers/internet_explorer Creates InternetExplorerOptions, enables useCreateProcessApiToLaunchIe, and launches the driver. Prints capabilities and quits. ```kotlin import org.openqa.selenium.Capabilities import org.openqa.selenium.ie.InternetExplorerDriver import org.openqa.selenium.ie.InternetExplorerOptions fun main() { val options = InternetExplorerOptions() options.useCreateProcessApiToLaunchIe() val driver = InternetExplorerDriver(options) try { driver.get("https://google.com/ncr") val caps = driver.getCapabilities() println(caps) } finally { driver.quit() } } ``` -------------------------------- ### Node registration with browser settings Source: https://www.selenium.dev/documentation/legacy/selenium_2/grid_2 Command-line example of registering a node with specific browser, version, and platform settings. ```bash -browser browserName=firefox,version=3.6,platform=LINUX ``` -------------------------------- ### Remote WebDriver Ruby example Source: https://www.selenium.dev/documentation/webdriver/drivers/remote_webdriver This RSpec example demonstrates using Selenium Remote WebDriver with a local Selenium server. It starts the server in the background, creates a remote driver session, and tests file upload and download functionality. The example requires a Selenium server jar file and uses Chrome options. ```ruby # frozen_string_literal: true require 'spec_helper' require 'selenium/server' RSpec.describe 'Remote WebDriver' do let(:target_directory) { File.join(Dir.tmpdir, SecureRandom.uuid) } let(:wait) { Selenium::WebDriver::Wait.new(timeout: 2) } let(:server) do Selenium::Server.new(File.expand_path(File.join('..', '..', '..', 'selenium-server-4.46.0.jar'), __dir__), background: true, args: %w[--selenium-manager true --enable-managed-downloads true]) end let(:grid_url) { server.webdriver_url } before { server.start } after { server.stop } it 'starts remotely' do options = Selenium::WebDriver::Options.chrome driver = Selenium::WebDriver.for :remote, url: grid_url, options: options expect { driver.session_id }.not_to raise_exception end it 'uploads' do options = Selenium::WebDriver::Options.chrome driver = Selenium::WebDriver.for :remote, url: server.webdriver_url, options: options driver.get('https://the-internet.herokuapp.com/upload') upload_file = File.expand_path('../spec_support/selenium-snapshot.png', __dir__) driver.file_detector = ->((filename, *)) { filename.include?('selenium') && filename } file_input = driver.find_element(css: 'input[type=file]') file_input.send_keys(upload_file) driver.find_element(id: 'file-submit').click wait.until { driver.find_element(id: 'uploaded-files') } expect(driver.find_element(id: 'uploaded-files').text).to eq 'selenium-snapshot.png' end it 'downloads' do options = Selenium::WebDriver::Options.chrome(enable_downloads: true) driver = Selenium::WebDriver.for :remote, url: grid_url, options: options file_names = %w[file_1.txt file_2.jpg] driver.get('https://www.selenium.dev/selenium/web/downloads/download.html') driver.find_element(id: 'file-1').click driver.find_element(id: 'file-2').click wait.until { driver.downloadable_files.include?('file_2.jpg') && driver.downloadable_files.include?('file_1.txt') } files = driver.downloadable_files expect(files.sort).to eq file_names.sort downloadable_file = 'file_1.txt' driver.download_file(downloadable_file, target_directory) file_content = File.read("#{target_directory}/#{downloadable_file}").strip expect(file_content).to eq('Hello, World!') driver.delete_downloadable_files expect(driver.downloadable_files).to be_empty end end ``` -------------------------------- ### List Selenium Grid commands with --config-help Source: https://www.selenium.dev/documentation/grid/configuration/help Run this command to show all available commands and their descriptions for Selenium Grid. ```bash java -jar selenium-server-.jar --config-help ``` -------------------------------- ### Get Text of Element (C#) Source: https://www.selenium.dev/documentation/webdriver/elements/information Retrieves the rendered text of an element identified by tag name 'h1' using the 'Text' property. This is a minimal example. ```csharp // GetText // Retrieves the text of the element string text = driver.FindElement(By.TagName("h1")).Text; ``` -------------------------------- ### Start standalone server from command line Source: https://www.selenium.dev/documentation/legacy/selenium_2/remote_server Starts the standalone server from the command line. Run this from the directory containing the downloaded selenium-server-standalone-{VERSION}.jar on the machine with the browser to test. ```bash java -jar selenium-server-standalone-{VERSION}.jar ``` -------------------------------- ### Get Text of Element (Python) Source: https://www.selenium.dev/documentation/webdriver/elements/information Retrieves the rendered text of an element identified by tag name 'h1' using the 'text' property. This is a minimal example. ```python text = driver.find_element(By.TAG_NAME, "h1").text ``` -------------------------------- ### Python: Full test_service example Source: https://www.selenium.dev/documentation/webdriver/drivers/service Complete Python test module demonstrating basic service, driver location, and driver port. Includes helper function for default Chrome options. ```python from selenium import webdriver def test_basic_service(): service = webdriver.ChromeService() driver = webdriver.Chrome(service=service) driver.quit() def test_driver_location(chromedriver_bin, chrome_bin): options = get_default_chrome_options() options.binary_location = chrome_bin service = webdriver.ChromeService(executable_path=chromedriver_bin) driver = webdriver.Chrome(service=service, options=options) driver.quit() def test_driver_port(): service = webdriver.ChromeService(port=1234) driver = webdriver.Chrome(service=service) driver.quit() def get_default_chrome_options(): options = webdriver.ChromeOptions() options.add_argument("--no-sandbox") return options ``` -------------------------------- ### Performance Metrics via CDP Source: https://www.selenium.dev/documentation/webdriver/bidi/cdp/network Enables performance metrics and retrieves them using CDP. The example shows how to get metrics after navigating to a frameset page. ```java @Test public void performanceMetrics() { driver.get("https://www.selenium.dev/selenium/web/frameset.html"); DevTools devTools = ((HasDevTools) driver).getDevTools(); devTools.createSession(); devTools.send(Performance.enable(Optional.empty())); List metricList = devTools.send(Performance.getMetrics()); } ``` -------------------------------- ### Navigate to the Kotlin directory Source: https://www.selenium.dev/documentation/webdriver/getting_started/first_script Changes the current directory to the Kotlin examples directory within the cloned repository. ```bash cd seleniumhq.github.io/examples/kotlin ``` -------------------------------- ### JavaScript Add and Get Cookie Source: https://www.selenium.dev/documentation/webdriver/interactions/cookies JavaScript example for setting a cookie on the current domain and retrieving its details. Uses Selenium WebDriver's manage API. ```javascript // set a cookie on the current domain await driver.manage().addCookie({ name: 'foo', value: 'bar' }); // Get cookie details with named cookie 'foo' ``` -------------------------------- ### JavaScript: Get alert text and accept Source: https://www.selenium.dev/documentation/webdriver/interactions/alerts JavaScript code to switch to an alert, retrieve its text, and accept it. This is a short example showing the basic alert interaction. ```javascript let alert = await driver.switchTo().alert(); let alertText = await alert.getText(); await alert.accept(); ``` -------------------------------- ### Start Browser in Python Source: https://www.selenium.dev/documentation/legacy/selenium_1 Creates a selenium instance with localhost, port 4444, Firefox, and Google URL, then starts it. The start() method is required to launch the browser. ```python self.selenium = selenium("localhost", 4444, "*firefox", "http://www.google.com/") self.selenium.start() ``` -------------------------------- ### Java: Complete ServiceTest example Source: https://www.selenium.dev/documentation/webdriver/drivers/service Full Java test class showing how to create a default service, set driver location, and set a custom port. Includes helper methods to find driver and browser paths using DriverFinder. ```java package dev.selenium.drivers; import dev.selenium.BaseTest; import java.io.File; import org.junit.jupiter.api.Test; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; import org.openqa.selenium.chrome.ChromeOptions; import org.openqa.selenium.remote.service.DriverFinder; public class ServiceTest extends BaseTest { @Test public void defaultService() { ChromeDriverService service = new ChromeDriverService.Builder().build(); driver = new ChromeDriver(service); } @Test public void setDriverLocation() { setBinaryPaths(); ChromeOptions options = getDefaultChromeOptions(); options.setBinary(browserPath); ChromeDriverService service = new ChromeDriverService.Builder().usingDriverExecutable(driverPath).build(); driver = new ChromeDriver(service, options); } @Test public void setPort() { ChromeDriverService service = new ChromeDriverService.Builder().usingPort(1234).build(); driver = new ChromeDriver(service); } private void setBinaryPaths() { ChromeOptions options = getDefaultChromeOptions(); options.setBrowserVersion("stable"); DriverFinder finder = new DriverFinder(ChromeDriverService.createDefaultService(), options); driverPath = new File(finder.getDriverPath()); browserPath = new File(finder.getBrowserPath()); } } ``` -------------------------------- ### C#: Network Authentication Handler Source: https://www.selenium.dev/documentation/webdriver/bidi/cdp/network C# example using Selenium's NetworkAuthenticationHandler to set credentials for basic authentication on a matching URI, then start monitoring. ```csharp var handler = new NetworkAuthenticationHandler() { UriMatcher = uri => uri.AbsoluteUri.Contains("herokuapp"), Credentials = new PasswordCredentials("admin", "admin") }; var networkInterceptor = driver.Manage().Network; networkInterceptor.AddAuthenticationHandler(handler); await networkInterceptor.StartMonitoring(); ``` -------------------------------- ### Kotlin: Pen actions test class Source: https://www.selenium.dev/documentation/webdriver/actions_api/pen Kotlin test class for pen actions, including imports and test setup. This example is from the Kotlin file PenTest.kt. ```kotlin package dev.selenium.actions_api import dev.selenium.BaseTest import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import org.openqa.selenium.By import org.openqa.selenium.WebElement import org.openqa.selenium.interactions.Actions import org.openqa.selenium.interactions.PointerInput import org.openqa.selenium.interactions.Sequence import org.openqa.selenium.remote.RemoteWebDriver import kotlin.collections.Map import java.time.Duration ``` -------------------------------- ### C#: First Script - Complete Example Source: https://www.selenium.dev/documentation/webdriver/drivers This C# example demonstrates a basic Selenium WebDriver script: it creates a ChromeDriver, navigates to a web form, gets the title, sets an implicit wait, finds and interacts with a text box and submit button, retrieves a message, and quits the driver. ```csharp using System; using OpenQA.Selenium; using OpenQA.Selenium.Chrome; namespace SeleniumDocs.GettingStarted; public static class FirstScript { public static void Main() { IWebDriver driver = new ChromeDriver(); driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/web-form.html"); var title = driver.Title; driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500); var textBox = driver.FindElement(By.Name("my-text")); var submitButton = driver.FindElement(By.TagName("button")); textBox.SendKeys("Selenium"); submitButton.Click(); var message = driver.FindElement(By.Id("message")); var value = message.Text; driver.Quit(); } } ``` -------------------------------- ### Start Browser in Ruby Source: https://www.selenium.dev/documentation/legacy/selenium_1 Initializes a Selenium::ClientDriver with localhost, port 4444, Firefox, Google URL, and a timeout of 10000 ms, then starts it. The start method is required. ```ruby @selenium = Selenium::ClientDriver.new("localhost", 4444, "*firefox", "http://www.google.com/", 10000); @selenium.start ``` -------------------------------- ### Get security help with info security Source: https://www.selenium.dev/documentation/grid/configuration/help Run this command to get details on setting up Grid servers for secure communication and node registration. ```bash java -jar selenium-server-.jar info security ``` -------------------------------- ### Wait for Download Source: https://www.selenium.dev/documentation/webdriver/bidi/cdp/network Navigates to a download page, gets the DevTools session, and prepares a temporary download path. The example is incomplete; the actual download waiting logic is not shown. ```csharp [TestMethod] public async Task WaitForDownload() { driver.Url = "https://www.selenium.dev/selenium/web/downloads/download.html"; var session = ((IDevTools)driver).GetDevToolsSession(); var domains = session.GetVersionSpecificDomains(); var downloadPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); Directory.CreateDirectory(downloadPath); } ``` -------------------------------- ### Get Jaeger UI Tracing Instructions Source: https://www.selenium.dev/documentation/grid/advanced_features/observability Prints detailed instructions for visualizing traces using Jaeger UI. Run this command to obtain setup and usage guidance. ```bash java -jar selenium-server-4.0.0-.jar info tracing ``` -------------------------------- ### se-config.toml Example Source: https://www.selenium.dev/documentation/selenium_manager Example configuration file for Selenium Manager. Shows all available options with their corresponding command-line flags. The file is named se-config.toml and includes settings for browser, driver, versions, paths, mirrors, output, OS, architecture, proxy, timeout, offline mode, and more. ```toml browser = "chrome" # --browser BROWSER driver = "chromedriver" # --driver DRIVER browser-version = "106" # --browser-version BROWSER_VERSION driver-version = "106.0.5249.61" # --driver-version DRIVER_VERSION browser-path = "/usr/bin/google-chrome" # --browser-path BROWSER_PATH driver-mirror-url = "https://custom-driver-mirror.com" # --driver-mirror-url DRIVER_MIRROR_URL browser-mirror-url = "https://custom-browser-mirror.com" # --browser-mirror-url BROWSER_MIRROR_URL output = "LOGGER" # --output OUTPUT os = "linux" # --os OS arch = "x64" # --arch ARCH proxy = "myproxy:8080" # --proxy PROXY timeout = 300 # --timeout TIMEOUT offline = true # --offline force-browser-download = true # --force-browser-download avoid-browser-download = false # --avoid-browser-download debug = true # --debug trace = true # --trace cache-path = "/custom/cache/path" # --cache-path CACHE_PATH ttl = 3600 # --ttl TTL language-binding = "Python" # --language-binding LANGUAGE avoid-stats = true # --avoid-stats ``` -------------------------------- ### Java: Complete FindersTest example Source: https://www.selenium.dev/documentation/webdriver/elements/finders Complete Java test class demonstrating various find element scenarios: finding first matching element, finding elements within a subset of the DOM, using an optimized locator, finding all matching elements, getting elements from a collection, and getting the active element. ```java package dev.selenium.elements; import dev.selenium.BaseTest; import org.junit.jupiter.api.Test; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; public class FindersTest extends BaseTest { private static final String LOCATORS_PAGE = "https://www.selenium.dev/selenium/web/locators_tests/locators.html"; @Test public void findsFirstMatchingElement() { startChromeDriver(); driver.get(LOCATORS_PAGE); WebElement firstInput = driver.findElement(By.className("information")); assertEquals("fname", firstInput.getAttribute("id")); } @Test public void findsElementWithinASubsetOfTheDom() { startChromeDriver(); driver.get(LOCATORS_PAGE); WebElement form = driver.findElement(By.tagName("form")); WebElement input = form.findElement(By.className("information")); assertEquals("fname", input.getAttribute("id")); } @Test public void usesAnOptimizedLocator() { startChromeDriver(); driver.get(LOCATORS_PAGE); WebElement input = driver.findElement(By.cssSelector("form .information")); assertEquals("fname", input.getAttribute("id")); } @Test public void findsAllMatchingElements() { startChromeDriver(); driver.get(LOCATORS_PAGE); List inputs = driver.findElements(By.tagName("input")); assertTrue(inputs.size() > 1); } @Test public void getsElementFromACollection() { startChromeDriver(); driver.get(LOCATORS_PAGE); List elements = driver.findElements(By.tagName("p")); for (WebElement element : elements) { System.out.println("Paragraph text:" + element.getText()); } assertTrue(elements.size() > 0); } @Test public void findsElementsFromElement() { startChromeDriver(); driver.get(LOCATORS_PAGE); WebElement form = driver.findElement(By.tagName("form")); List elements = form.findElements(By.tagName("input")); for (WebElement e : elements) { System.out.println(e.getAttribute("value")); } assertTrue(elements.size() > 0); } @Test public void getsActiveElement() { startChromeDriver(); driver.get(LOCATORS_PAGE); driver.findElement(By.cssSelector("#fname")).sendKeys("webElement"); String attr = driver.switchTo().activeElement().getAttribute("name"); assertEquals("fname", attr); } } ```