Finding web elements

Locating the elements based on the provided locator values.

One of the most fundamental aspects of using Selenium is obtaining element references to work with. Selenium offers a number of built-in locator strategies to uniquely identify an element. There are many ways to use the locators in very advanced scenarios. For the purposes of this documentation, use the Selenium locator test page.

First matching element

Many locators will match multiple elements on the page. The singular find element method will return a reference to the first element found within a given context.

Evaluating entire DOM

When the find element method is called on the driver instance, it returns a reference to the first element in the DOM that matches with the provided locator. This value can be stored and used for future element actions. On the Selenium locator test page, there are two elements with the class name information, so this method returns the first text input.

Move Code

driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
WebElement firstInput = driver.findElement(By.className("information"));
  
# same examples are shown for the other language bindings:
  #
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
var firstInput = driver.FindElement(By.ClassName("information"));
  
      driver.find_element(class: 'tomatoes')
    end
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const firstInput = await driver.findElement(By.className('information'));
  
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
val firstInput: WebElement = driver.findElement(By.className("information"))
  

Evaluating a subset of the DOM

Rather than finding a unique locator in the entire DOM, it is often useful to narrow the search to the scope of another located element.

One solution is to locate an ancestor of the desired element, then call find element on that object:

Move Code

driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
WebElement form = driver.findElement(By.tagName("form"));
WebElement input = form.findElement(By.className("information"));
  
# <ul id="fruits">
  #   <li class="bananas">…
  #   <li class="apples">…
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
IWebElement form = driver.FindElement(By.TagName("form"));
IWebElement input = form.FindElement(By.ClassName("information"));
  

    it 'uses an optimized locator' do
      driver.find_element(css: '#fruits .tomatoes')
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const form = await driver.findElement(By.tagName('form'));
const input = await form.findElement(By.className('information'));
  
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
val form = driver.findElement(By.tagName("form"))
val input = form.findElement(By.className("information"))
  

Java and C#
WebDriver, WebElement and ShadowRoot classes all implement a SearchContext interface, which is considered a role-based interface. Role-based interfaces allow you to determine whether a particular driver implementation supports a given feature. These interfaces are clearly defined and try to adhere to having only a single role of responsibility.

Evaluating the Shadow DOM

The Shadow DOM is an encapsulated DOM tree hidden inside an element. With the release of v96 in Chromium Browsers, Selenium can now allow you to access this tree with easy-to-use shadow root methods. NOTE: These methods require Selenium 4.0 or greater.

Move Code

WebElement shadowHost = driver.findElement(By.cssSelector("#shadow_host"));
SearchContext shadowRoot = shadowHost.getShadowRoot();
WebElement shadowContent = shadowRoot.findElement(By.cssSelector("#shadow_content"));
    plants = driver.find_elements(By.TAG_NAME, 'li')


def test_evaluating_shadow_dom():
var shadowHost = _driver.FindElement(By.CssSelector("#shadow_host"));
var shadowRoot = shadowHost.GetShadowRoot();
var shadowContent = shadowRoot.FindElement(By.CssSelector("#shadow_content"));
shadow_host = @driver.find_element(css: '#shadow_host')
shadow_root = shadow_host.shadow_root
shadow_content = shadow_root.find_element(css: '#shadow_content')

Optimized locator

A nested lookup might not be the most effective location strategy since it requires two separate commands to be issued to the browser.

To improve the performance slightly, we can use either CSS or XPath to find this element in a single command. See the Locator strategy suggestions in our Encouraged test practices section.

For this example, we’ll use a CSS selector:

Move Code

driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
WebElement input = driver.findElement(By.cssSelector("form .information"));
  
def test_basic_finders(driver):
      vegetable = driver.find_element(By.CLASS_NAME, 'tomatoes')
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
var input = driver.FindElement(By.CssSelector("form .information"));
  

    # rubocop:disable RSpec/Output
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const input = await driver.findElement(By.css('form .information'));
  
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
val input = driver.findElement(By.cssSelector("form .information"))
  

All matching elements

There are several use cases for needing to get references to all elements that match a locator, rather than just the first one. The plural find elements methods return a collection of element references. If there are no matches, an empty list is returned. In this case, references to all input elements will be returned in a collection.

Move Code

driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
List<WebElement> inputs = driver.findElements(By.tagName("input"));
  
    fruit = fruits.find_element(By.CLASS_NAME, 'tomatoes')
  
driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
IReadOnlyList<IWebElement> inputs = driver.FindElements(By.TagName("input"));
  
    it 'finds element from element' do
      element = driver.find_element(:tag_name, 'div')
await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
const inputs = await driver.findElements(By.tagName('input'));
  
driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
val inputs: List<WebElement> = driver.findElements(By.tagName("input"))
  

Get element

Often you get a collection of elements but want to work with a specific element, which means you need to iterate over the collection and identify the one you want.

Move Code

driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
List<WebElement> elements = driver.findElements(By.tagName("p"));

for (WebElement element : elements) {
    System.out.println("Paragraph text:" + element.getText());
}
  

      assert shadow_host.is_displayed()
      assert shadow_content.is_displayed()
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using System.Collections.Generic;

namespace FindElementsExample {
 class FindElementsExample {
  public static void Main(string[] args) {
   IWebDriver driver = new FirefoxDriver();
   try {
    // Navigate to Url
    driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");

    // Get all the elements available with tag name 'p'
    IList < IWebElement > elements = driver.FindElements(By.TagName("p"));
    foreach(IWebElement e in elements) {
     System.Console.WriteLine(e.Text);
    }

   } finally {
    driver.Quit();
   }
  }
 }
}
  
      driver.find_element(css: '[name="q"]').send_keys('webElement')
         driver.switch_to.active_element.attribute('title')
       end
const {Builder, By} = require('selenium-webdriver');
(async function example() {
    let driver = await new Builder().forBrowser('firefox').build();
    try {
        // Navigate to Url
        await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');

        // Get all the elements available with tag 'p'
        let elements = await driver.findElements(By.css('p'));
        for(let e of elements) {
            console.log(await e.getText());
        }
    }
    finally {
        await driver.quit();
    }
})();
  
import org.openqa.selenium.By
import org.openqa.selenium.firefox.FirefoxDriver

fun main() {
    val driver = FirefoxDriver()
    try {
        driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
        // Get all the elements available with tag name 'p'
        val elements = driver.findElements(By.tagName("p"))
        for (element in elements) {
            println("Paragraph text:" + element.text)
        }
    } finally {
        driver.quit()
    }
}
  

Find Elements From Element

It is used to find the list of matching child WebElements within the context of parent element. To achieve this, the parent WebElement is chained with ‘findElements’ to access child elements

Move Code

  import org.openqa.selenium.By;
  import org.openqa.selenium.WebDriver;
  import org.openqa.selenium.WebElement;
  import org.openqa.selenium.chrome.ChromeDriver;
  import java.util.List;

  public class findElementsFromElement {
      public static void main(String[] args) {
          WebDriver driver = new ChromeDriver();
          try {
              driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");

              // Get the form element
              WebElement element = driver.findElement(By.tagName("form"));

              // Get all input elements in the form
              List<WebElement> elements = element.findElements(By.tagName("input"));
              for (WebElement e : elements) {
                  System.out.println(e.getAttribute("value"));
              }
          } finally {
              driver.quit();
          }
      }
  }
  

      elements = driver.find_elements(By.TAG_NAME, 'p')
      for element in elements:
          print(element.text)
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using System.Collections.Generic;

namespace FindElementsFromElement {
 class FindElementsFromElement {
  public static void Main(string[] args) {
   IWebDriver driver = new ChromeDriver();
   try {
    driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");

    // Get the form element
    IWebElement element = driver.FindElement(By.TagName("form"));

    // Get all input elements in the form
    IList < IWebElement > elements = element.FindElements(By.TagName("input"));
    foreach(IWebElement e in elements) {
     System.Console.WriteLine(e.GetAttribute("value"));
    }
   } finally {
    driver.Quit();
   }
  }
 }
}
  
  const {Builder, By} = require('selenium-webdriver');

  (async function example() {
      let driver = new Builder()
          .forBrowser('chrome')
          .build();

      await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');

      // Get the form element
      let element = driver.findElement(By.css("form"));

      // Get all input elements in the form
      let elements = await element.findElements(By.css("input"));
      for(let e of elements) {
          console.log(await e.getAttribute("value"));
      }
  })();
  
  import org.openqa.selenium.By
  import org.openqa.selenium.chrome.ChromeDriver

  fun main() {
      val driver = ChromeDriver()
      try {
          driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")

          // Get the form element
          val element = driver.findElement(By.tagName("form"))

          // Get all input elements in the form
          val elements = element.findElements(By.tagName("input"))
          for (e in elements) {
              println(e.getAttribute("value"))
          }
      } finally {
          driver.quit()
      }
  }
  

Get Active Element

It is used to track (or) find DOM element which has the focus in the current browsing context.

Move Code

  import org.openqa.selenium.*;
  import org.openqa.selenium.chrome.ChromeDriver;

  public class activeElementTest {
    public static void main(String[] args) {
      WebDriver driver = new ChromeDriver();
      try {
        driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
        driver.findElement(By.cssSelector("#fname")).sendKeys("webElement");

        // Get attribute of current active element
        String attr = driver.switchTo().activeElement().getAttribute("name");
        System.out.println(attr);
      } finally {
        driver.quit();
      }
    }
  }
  
    driver = webdriver.Chrome()
      driver.get('https://www.example.com')
    using OpenQA.Selenium;
    using OpenQA.Selenium.Chrome;

    namespace ActiveElement {
     class ActiveElement {
      public static void Main(string[] args) {
       IWebDriver driver = new ChromeDriver();
       try {
        // Navigate to Url
        driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");
        driver.FindElement(By.CssSelector("#fname")).SendKeys("webElement");

        // Get attribute of current active element
        string attr = driver.SwitchTo().ActiveElement().GetAttribute("name");
        System.Console.WriteLine(attr);
       } finally {
        driver.Quit();
       }
      }
     }
    }
  
  const {Builder, By} = require('selenium-webdriver');

  (async function example() {
      let driver = await new Builder().forBrowser('chrome').build();
      await driver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');
      await driver.findElement(By.css('#fname')).sendKeys("webElement");

      // Get attribute of current active element
      let attr = await driver.switchTo().activeElement().getAttribute("name");
      console.log(`${attr}`)
  })();
  
  import org.openqa.selenium.By
  import org.openqa.selenium.chrome.ChromeDriver

  fun main() {
      val driver = ChromeDriver()
      try {
          driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")
          driver.findElement(By.cssSelector("#fname")).sendKeys("webElement")

          // Get attribute of current active element
          val attr = driver.switchTo().activeElement().getAttribute("name")
          print(attr)
      } finally {
          driver.quit()
      }
  }