Write your first Selenium script
Once you have Selenium installed and Drivers installed, you’re ready to write Selenium code.
Eight Basic Components
Everything Selenium does is send the browser commands to do something or send requests for information. Most of what you’ll do with Selenium is a combination of these basic commands:
1. Start the session
For more details on starting a session read our documentation on opening and closing a browser
driver = new ChromeDriver();
driver = webdriver.Chrome()
var driver = new ChromeDriver();
driver = Selenium::WebDriver.for :chrome
let driver = await new Builder().forBrowser('chrome').build();
driver = ChromeDriver()
2. Take action on browser
In this example we are navigating to a web page.
driver.get("https://google.com");
driver.get("https://google.com")
driver.Navigate().GoToUrl("https://google.com");
driver.get('https://google.com')
await driver.get('https://www.google.com');
driver.get("https://google.com")
3. Request browser information
There are a bunch of types of information about the browser you can request, including window handles, browser size / position, cookies, alerts, etc.
String title = driver.getTitle();
title = driver.title
var title = driver.Title;
title = driver.title
await driver.getTitle();
title = driver.title
4. Establish Waiting Strategy
Synchronizing the code with the current state of the browser is one of the biggest challenges with Selenium, and doing it well is an advanced topic.
Essentially you want to make sure that the element is on the page before you attempt to locate it and the element is in an interactable state before you attempt to interact with it.
An implicit wait is rarely the best solution, but it’s the easiest to demonstrate here, so we’ll use it as a placeholder.
Read more about Waiting strategies.
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
driver.implicitly_wait(0.5)
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
driver.manage.timeouts.implicit_wait = 500
await driver.manage().setTimeouts({implicit: 1000})
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500))
5. Find an element
The majority of commands in most Selenium sessions are element related, and you can’t interact with one without first finding an element
WebElement searchBox = driver.findElement(By.name("q"));
WebElement searchButton = driver.findElement(By.name("btnK"));
search_box = driver.find_element(by=By.NAME, value="q")
search_button = driver.find_element(by=By.NAME, value="btnK")
var searchBox = driver.FindElement(By.Name("q"));
var searchButton = driver.FindElement(By.Name("btnK"));
search_box = driver.find_element(name: 'q')
search_button = driver.find_element(name: 'btnK')
let searchBox = await driver.findElement(By.name('q'));
let searchButton = await driver.findElement(By.name('btnK'));
var searchBox = driver.findElement(By.name("q"))
val searchButton = driver.findElement(By.name("btnK"))
6. Take action on element
There are only a handful of actions to take on an element, but you will use them frequently.
searchBox.sendKeys("Selenium");
searchButton.click();
search_box.send_keys("Selenium")
search_button.click()
searchBox.SendKeys("Selenium");
searchButton.Click();
search_box.send_keys('Selenium')
search_button.click
await searchBox.sendKeys('Selenium');
await searchButton.click();
searchBox.sendKeys("Selenium")
searchButton.click()
7. Request element information
Elements store a lot of information that can be requested. Notice that we need to relocate the search box because the DOM has changed since we first located it.
String value = searchBox.getAttribute("value");
value = search_box.get_attribute("value")
var value = searchBox.GetAttribute("value");
value = search_box.attribute('value')
let value = await searchBox.getAttribute("value");
val value = searchBox.getAttribute("value")
8. End the session
This ends the driver process, which by default closes the browser as well. No more commands can be sent to this driver instance.
driver.quit();
driver.quit()
driver.Quit();
driver.quit
await driver.quit();
driver.quit()
Putting everything together
Let’s combine these 8 things into a complete script with assertions that can be executed by a test runner.
package dev.selenium.getting_started;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
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 FirstScriptTest {
public WebDriver driver;
@Test
public void eightComponents() {
driver = new ChromeDriver();
driver.get("https://google.com");
String title = driver.getTitle();
Assertions.assertEquals("Google", title);
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500));
WebElement searchBox = driver.findElement(By.name("q"));
WebElement searchButton = driver.findElement(By.name("btnK"));
searchBox.sendKeys("Selenium");
searchButton.click();
searchBox = driver.findElement(By.name("q"));
String value = searchBox.getAttribute("value");
Assertions.assertEquals("Selenium", value);
driver.quit();
}
}
from selenium import webdriver
from selenium.webdriver.common.by import By
def test_eight_components():
driver = webdriver.Chrome()
driver.get("https://google.com")
title = driver.title
assert title == "Google"
driver.implicitly_wait(0.5)
search_box = driver.find_element(by=By.NAME, value="q")
search_button = driver.find_element(by=By.NAME, value="btnK")
search_box.send_keys("Selenium")
search_button.click()
search_box = driver.find_element(by=By.NAME, value="q")
value = search_box.get_attribute("value")
assert value == "Selenium"
driver.quit()
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
namespace SeleniumDocs.GettingStarted
{
[TestClass]
public class FirstScriptTest
{
[TestMethod]
public void ChromeSession()
{
var driver = new ChromeDriver();
driver.Navigate().GoToUrl("https://google.com");
var title = driver.Title;
Assert.AreEqual("Google", title);
driver.Manage().Timeouts().ImplicitWait = TimeSpan.FromMilliseconds(500);
var searchBox = driver.FindElement(By.Name("q"));
var searchButton = driver.FindElement(By.Name("btnK"));
searchBox.SendKeys("Selenium");
searchButton.Click();
searchBox = driver.FindElement(By.Name("q"));
var value = searchBox.GetAttribute("value");
Assert.AreEqual("Selenium", value);
driver.Quit();
}
}
}
# frozen_string_literal: true
RSpec.describe 'First Script' do
it 'uses eight components' do
driver = Selenium::WebDriver.for :chrome
driver.get('https://google.com')
title = driver.title
expect(title).to eq('Google')
driver.manage.timeouts.implicit_wait = 500
search_box = driver.find_element(name: 'q')
search_button = driver.find_element(name: 'btnK')
search_box.send_keys('Selenium')
search_button.click
search_box = driver.find_element(name: 'q')
value = search_box.attribute('value')
expect(value).to eq('Selenium')
driver.quit
end
end
const {Builder, By} = require('selenium-webdriver');
const assert = require('assert');
(async function firstScript() {
try {
let driver = await new Builder().forBrowser('chrome').build();
await driver.get('https://www.google.com');
await driver.getTitle();
await driver.manage().setTimeouts({implicit: 1000})
let searchBox = await driver.findElement(By.name('q'));
let searchButton = await driver.findElement(By.name('btnK'));
await searchBox.sendKeys('Selenium');
await searchButton.click();
let value = await searchBox.getAttribute("value");
assert.deepStrictEqual(value, "Selenium")
await driver.quit();
} catch (error) {
console.log(error)
}
})();
package dev.selenium.getting_started
import io.github.bonigarcia.wdm.WebDriverManager
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.openqa.selenium.By
import org.openqa.selenium.WebDriver
import org.openqa.selenium.chrome.ChromeDriver
import java.time.Duration
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class FirstScriptTest {
private lateinit var driver: WebDriver
@Test
fun eightComponents() {
driver = ChromeDriver()
driver.get("https://google.com")
title = driver.title
assertEquals("Google", title)
driver.manage().timeouts().implicitlyWait(Duration.ofMillis(500))
var searchBox = driver.findElement(By.name("q"))
val searchButton = driver.findElement(By.name("btnK"))
searchBox.sendKeys("Selenium")
searchButton.click()
searchBox = driver.findElement(By.name("q"))
val value = searchBox.getAttribute("value")
assertEquals("Selenium", value)
driver.quit()
}
}
Next Steps
Take what you’ve learned and build out your Selenium code.
As you find more functionality that you need, read up on the rest of our WebDriver documentation.