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,
let’s consider this HTML snippet:
<olid="vegetables"><liclass="potatoes">…
<liclass="onions">…
<liclass="tomatoes"><span>Tomato is a Vegetable</span>…
</ol><ulid="fruits"><liclass="bananas">…
<liclass="apples">…
<liclass="tomatoes"><span>Tomato is a Fruit</span>…
</ul>
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. In our example HTML above, there are
two elements that have a class name of “tomatoes” so this method will return the element in the “vegetables” list.
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_finders():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')body_on_page=driver.find_element(By.CLASS_NAME,'td-home')container_on_page=body_on_page.find_element(By.CLASS_NAME,'container-fluid')assertcontainer_on_page.is_displayed()driver.quit()deftest_evaluating_shadow_DOM():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')custom_element=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_dom_input=custom_element.shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertcustom_element.is_displayed()assertcustom_element.shadow_rootassertshadow_dom_input.is_displayed()driver.quit()deftest_optimized_locator():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')nested_element=driver.find_element(By.CSS_SELECTOR,'.td-home #announcement-banner')assertnested_element.is_displayed()driver.quit()deftest_all_matching_elements():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')header_two_elements=driver.find_elements(By.TAG_NAME,'h2')assertlen(header_two_elements)>1forheader_elementinheader_two_elements:print(header_element.text)driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')main_element=driver.find_element(By.TAG_NAME,'main')svg_elements=main_element.find_elements(By.TAG_NAME,'svg')forsvg_elementinsvg_elements:print(svg_element.is_displayed())## get elements from parent element using XPATH## NOTE: in order to utilize XPATH from current element, you must add "." to beginning of pathheader_tag=driver.find_element(By.TAG_NAME,'header')# Get first element of tag 'ul'ul_tag=header_tag.find_element(By.XPATH,'//ul')# get children of tag 'ul' with tag 'li'elements=ul_tag.find_elements(By.XPATH,'.//li')forelementinelements:print(element.text)assertlen(elements)>0assertlen(svg_elements)>1driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')dropdown=driver.find_element(By.CSS_SELECTOR,'.nav-item.dropdown')dropdown.click()active_element=driver.switch_to.active_elementassertactive_element.get_attribute('href').endswith('#')driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Element Finders'dolet(:driver){start_session}context'without executing finders',skip:'these are just examples, not actual tests'doit'finds the first matching element'dodriver.find_element(class:'tomatoes')endit'uses a subset of the dom to find an element'dofruits=driver.find_element(id:'fruits')fruits.find_element(class:'tomatoes')endit'uses an optimized locator'dodriver.find_element(css:'#fruits .tomatoes')endit'finds all matching elements'dodriver.find_elements(tag_name:'li')endit'gets an element from a collection'doelements=driver.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'finds element from element'doelement=driver.find_element(:tag_name,'div')elements=element.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
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. In the above example there are two elements with a class name of “tomatoes” and
it is a little more challenging to get the reference for the second one.
One solution is to locate an element with a unique attribute that is an ancestor of the desired element and not an
ancestor of the undesired element, then call find element on that object:
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_finders():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')body_on_page=driver.find_element(By.CLASS_NAME,'td-home')container_on_page=body_on_page.find_element(By.CLASS_NAME,'container-fluid')assertcontainer_on_page.is_displayed()driver.quit()deftest_evaluating_shadow_DOM():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')custom_element=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_dom_input=custom_element.shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertcustom_element.is_displayed()assertcustom_element.shadow_rootassertshadow_dom_input.is_displayed()driver.quit()deftest_optimized_locator():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')nested_element=driver.find_element(By.CSS_SELECTOR,'.td-home #announcement-banner')assertnested_element.is_displayed()driver.quit()deftest_all_matching_elements():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')header_two_elements=driver.find_elements(By.TAG_NAME,'h2')assertlen(header_two_elements)>1forheader_elementinheader_two_elements:print(header_element.text)driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')main_element=driver.find_element(By.TAG_NAME,'main')svg_elements=main_element.find_elements(By.TAG_NAME,'svg')forsvg_elementinsvg_elements:print(svg_element.is_displayed())## get elements from parent element using XPATH## NOTE: in order to utilize XPATH from current element, you must add "." to beginning of pathheader_tag=driver.find_element(By.TAG_NAME,'header')# Get first element of tag 'ul'ul_tag=header_tag.find_element(By.XPATH,'//ul')# get children of tag 'ul' with tag 'li'elements=ul_tag.find_elements(By.XPATH,'.//li')forelementinelements:print(element.text)assertlen(elements)>0assertlen(svg_elements)>1driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')dropdown=driver.find_element(By.CSS_SELECTOR,'.nav-item.dropdown')dropdown.click()active_element=driver.switch_to.active_elementassertactive_element.get_attribute('href').endswith('#')driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Element Finders'dolet(:driver){start_session}context'without executing finders',skip:'these are just examples, not actual tests'doit'finds the first matching element'dodriver.find_element(class:'tomatoes')endit'uses a subset of the dom to find an element'dofruits=driver.find_element(id:'fruits')fruits.find_element(class:'tomatoes')endit'uses an optimized locator'dodriver.find_element(css:'#fruits .tomatoes')endit'finds all matching elements'dodriver.find_elements(tag_name:'li')endit'gets an element from a collection'doelements=driver.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'finds element from element'doelement=driver.find_element(:tag_name,'div')elements=element.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
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.
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_finders():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')body_on_page=driver.find_element(By.CLASS_NAME,'td-home')container_on_page=body_on_page.find_element(By.CLASS_NAME,'container-fluid')assertcontainer_on_page.is_displayed()driver.quit()deftest_evaluating_shadow_DOM():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')custom_element=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_dom_input=custom_element.shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertcustom_element.is_displayed()assertcustom_element.shadow_rootassertshadow_dom_input.is_displayed()driver.quit()deftest_optimized_locator():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')nested_element=driver.find_element(By.CSS_SELECTOR,'.td-home #announcement-banner')assertnested_element.is_displayed()driver.quit()deftest_all_matching_elements():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')header_two_elements=driver.find_elements(By.TAG_NAME,'h2')assertlen(header_two_elements)>1forheader_elementinheader_two_elements:print(header_element.text)driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')main_element=driver.find_element(By.TAG_NAME,'main')svg_elements=main_element.find_elements(By.TAG_NAME,'svg')forsvg_elementinsvg_elements:print(svg_element.is_displayed())## get elements from parent element using XPATH## NOTE: in order to utilize XPATH from current element, you must add "." to beginning of pathheader_tag=driver.find_element(By.TAG_NAME,'header')# Get first element of tag 'ul'ul_tag=header_tag.find_element(By.XPATH,'//ul')# get children of tag 'ul' with tag 'li'elements=ul_tag.find_elements(By.XPATH,'.//li')forelementinelements:print(element.text)assertlen(elements)>0assertlen(svg_elements)>1driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')dropdown=driver.find_element(By.CSS_SELECTOR,'.nav-item.dropdown')dropdown.click()active_element=driver.switch_to.active_elementassertactive_element.get_attribute('href').endswith('#')driver.quit()
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_finders():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')body_on_page=driver.find_element(By.CLASS_NAME,'td-home')container_on_page=body_on_page.find_element(By.CLASS_NAME,'container-fluid')assertcontainer_on_page.is_displayed()driver.quit()deftest_evaluating_shadow_DOM():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')custom_element=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_dom_input=custom_element.shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertcustom_element.is_displayed()assertcustom_element.shadow_rootassertshadow_dom_input.is_displayed()driver.quit()deftest_optimized_locator():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')nested_element=driver.find_element(By.CSS_SELECTOR,'.td-home #announcement-banner')assertnested_element.is_displayed()driver.quit()deftest_all_matching_elements():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')header_two_elements=driver.find_elements(By.TAG_NAME,'h2')assertlen(header_two_elements)>1forheader_elementinheader_two_elements:print(header_element.text)driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')main_element=driver.find_element(By.TAG_NAME,'main')svg_elements=main_element.find_elements(By.TAG_NAME,'svg')forsvg_elementinsvg_elements:print(svg_element.is_displayed())## get elements from parent element using XPATH## NOTE: in order to utilize XPATH from current element, you must add "." to beginning of pathheader_tag=driver.find_element(By.TAG_NAME,'header')# Get first element of tag 'ul'ul_tag=header_tag.find_element(By.XPATH,'//ul')# get children of tag 'ul' with tag 'li'elements=ul_tag.find_elements(By.XPATH,'.//li')forelementinelements:print(element.text)assertlen(elements)>0assertlen(svg_elements)>1driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')dropdown=driver.find_element(By.CSS_SELECTOR,'.nav-item.dropdown')dropdown.click()active_element=driver.switch_to.active_elementassertactive_element.get_attribute('href').endswith('#')driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Element Finders'dolet(:driver){start_session}context'without executing finders',skip:'these are just examples, not actual tests'doit'finds the first matching element'dodriver.find_element(class:'tomatoes')endit'uses a subset of the dom to find an element'dofruits=driver.find_element(id:'fruits')fruits.find_element(class:'tomatoes')endit'uses an optimized locator'dodriver.find_element(css:'#fruits .tomatoes')endit'finds all matching elements'dodriver.find_elements(tag_name:'li')endit'gets an element from a collection'doelements=driver.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'finds element from element'doelement=driver.find_element(:tag_name,'div')elements=element.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
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 fruits and vegetable list items will be returned in a collection.
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_finders():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')body_on_page=driver.find_element(By.CLASS_NAME,'td-home')container_on_page=body_on_page.find_element(By.CLASS_NAME,'container-fluid')assertcontainer_on_page.is_displayed()driver.quit()deftest_evaluating_shadow_DOM():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')custom_element=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_dom_input=custom_element.shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertcustom_element.is_displayed()assertcustom_element.shadow_rootassertshadow_dom_input.is_displayed()driver.quit()deftest_optimized_locator():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')nested_element=driver.find_element(By.CSS_SELECTOR,'.td-home #announcement-banner')assertnested_element.is_displayed()driver.quit()deftest_all_matching_elements():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')header_two_elements=driver.find_elements(By.TAG_NAME,'h2')assertlen(header_two_elements)>1forheader_elementinheader_two_elements:print(header_element.text)driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')main_element=driver.find_element(By.TAG_NAME,'main')svg_elements=main_element.find_elements(By.TAG_NAME,'svg')forsvg_elementinsvg_elements:print(svg_element.is_displayed())## get elements from parent element using XPATH## NOTE: in order to utilize XPATH from current element, you must add "." to beginning of pathheader_tag=driver.find_element(By.TAG_NAME,'header')# Get first element of tag 'ul'ul_tag=header_tag.find_element(By.XPATH,'//ul')# get children of tag 'ul' with tag 'li'elements=ul_tag.find_elements(By.XPATH,'.//li')forelementinelements:print(element.text)assertlen(elements)>0assertlen(svg_elements)>1driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')dropdown=driver.find_element(By.CSS_SELECTOR,'.nav-item.dropdown')dropdown.click()active_element=driver.switch_to.active_elementassertactive_element.get_attribute('href').endswith('#')driver.quit()
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Element Finders'dolet(:driver){start_session}context'without executing finders',skip:'these are just examples, not actual tests'doit'finds the first matching element'dodriver.find_element(class:'tomatoes')endit'uses a subset of the dom to find an element'dofruits=driver.find_element(id:'fruits')fruits.find_element(class:'tomatoes')endit'uses an optimized locator'dodriver.find_element(css:'#fruits .tomatoes')endit'finds all matching elements'dodriver.find_elements(tag_name:'li')endit'gets an element from a collection'doelements=driver.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'finds element from element'doelement=driver.find_element(:tag_name,'div')elements=element.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
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.
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_finders():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')body_on_page=driver.find_element(By.CLASS_NAME,'td-home')container_on_page=body_on_page.find_element(By.CLASS_NAME,'container-fluid')assertcontainer_on_page.is_displayed()driver.quit()deftest_evaluating_shadow_DOM():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')custom_element=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_dom_input=custom_element.shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertcustom_element.is_displayed()assertcustom_element.shadow_rootassertshadow_dom_input.is_displayed()driver.quit()deftest_optimized_locator():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')nested_element=driver.find_element(By.CSS_SELECTOR,'.td-home #announcement-banner')assertnested_element.is_displayed()driver.quit()deftest_all_matching_elements():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')header_two_elements=driver.find_elements(By.TAG_NAME,'h2')assertlen(header_two_elements)>1forheader_elementinheader_two_elements:print(header_element.text)driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')main_element=driver.find_element(By.TAG_NAME,'main')svg_elements=main_element.find_elements(By.TAG_NAME,'svg')forsvg_elementinsvg_elements:print(svg_element.is_displayed())## get elements from parent element using XPATH## NOTE: in order to utilize XPATH from current element, you must add "." to beginning of pathheader_tag=driver.find_element(By.TAG_NAME,'header')# Get first element of tag 'ul'ul_tag=header_tag.find_element(By.XPATH,'//ul')# get children of tag 'ul' with tag 'li'elements=ul_tag.find_elements(By.XPATH,'.//li')forelementinelements:print(element.text)assertlen(elements)>0assertlen(svg_elements)>1driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')dropdown=driver.find_element(By.CSS_SELECTOR,'.nav-item.dropdown')dropdown.click()active_element=driver.switch_to.active_elementassertactive_element.get_attribute('href').endswith('#')driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Firefox;usingSystem.Collections.Generic;namespaceFindElementsExample{classFindElementsExample{publicstaticvoidMain(string[]args){IWebDriverdriver=newFirefoxDriver();try{// Navigate to Urldriver.Navigate().GoToUrl("https://example.com");// Get all the elements available with tag name 'p'IList<IWebElement>elements=driver.FindElements(By.TagName("p"));foreach(IWebElementeinelements){System.Console.WriteLine(e.Text);}}finally{driver.Quit();}}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Element Finders'dolet(:driver){start_session}context'without executing finders',skip:'these are just examples, not actual tests'doit'finds the first matching element'dodriver.find_element(class:'tomatoes')endit'uses a subset of the dom to find an element'dofruits=driver.find_element(id:'fruits')fruits.find_element(class:'tomatoes')endit'uses an optimized locator'dodriver.find_element(css:'#fruits .tomatoes')endit'finds all matching elements'dodriver.find_elements(tag_name:'li')endit'gets an element from a collection'doelements=driver.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'finds element from element'doelement=driver.find_element(:tag_name,'div')elements=element.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
const{Builder,By}=require('selenium-webdriver');(asyncfunctionexample(){letdriver=awaitnewBuilder().forBrowser('firefox').build();try{// Navigate to Url
awaitdriver.get('https://www.example.com');// Get all the elements available with tag 'p'
letelements=awaitdriver.findElements(By.css('p'));for(leteofelements){console.log(awaite.getText());}}finally{awaitdriver.quit();}})();
importorg.openqa.selenium.Byimportorg.openqa.selenium.firefox.FirefoxDriverfunmain(){valdriver=FirefoxDriver()try{driver.get("https://example.com")// Get all the elements available with tag name 'p'
valelements=driver.findElements(By.tagName("p"))for(elementinelements){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
importorg.openqa.selenium.By;importorg.openqa.selenium.WebDriver;importorg.openqa.selenium.WebElement;importorg.openqa.selenium.chrome.ChromeDriver;importjava.util.List;publicclassfindElementsFromElement{publicstaticvoidmain(String[]args){WebDriverdriver=newChromeDriver();try{driver.get("https://example.com");// Get element with tag name 'div'WebElementelement=driver.findElement(By.tagName("div"));// Get all the elements available with tag name 'p'List<WebElement>elements=element.findElements(By.tagName("p"));for(WebElemente:elements){System.out.println(e.getText());}}finally{driver.quit();}}}
header_tag=driver.find_element(By.TAG_NAME,'header')# Get first element of tag 'ul'ul_tag=header_tag.find_element(By.XPATH,'//ul')# get children of tag 'ul' with tag 'li'elements=ul_tag.find_elements(By.XPATH,'.//li')forelementinelements:print(element.text)
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_finders():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')body_on_page=driver.find_element(By.CLASS_NAME,'td-home')container_on_page=body_on_page.find_element(By.CLASS_NAME,'container-fluid')assertcontainer_on_page.is_displayed()driver.quit()deftest_evaluating_shadow_DOM():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')custom_element=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_dom_input=custom_element.shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertcustom_element.is_displayed()assertcustom_element.shadow_rootassertshadow_dom_input.is_displayed()driver.quit()deftest_optimized_locator():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')nested_element=driver.find_element(By.CSS_SELECTOR,'.td-home #announcement-banner')assertnested_element.is_displayed()driver.quit()deftest_all_matching_elements():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')header_two_elements=driver.find_elements(By.TAG_NAME,'h2')assertlen(header_two_elements)>1forheader_elementinheader_two_elements:print(header_element.text)driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')main_element=driver.find_element(By.TAG_NAME,'main')svg_elements=main_element.find_elements(By.TAG_NAME,'svg')forsvg_elementinsvg_elements:print(svg_element.is_displayed())## get elements from parent element using XPATH## NOTE: in order to utilize XPATH from current element, you must add "." to beginning of pathheader_tag=driver.find_element(By.TAG_NAME,'header')# Get first element of tag 'ul'ul_tag=header_tag.find_element(By.XPATH,'//ul')# get children of tag 'ul' with tag 'li'elements=ul_tag.find_elements(By.XPATH,'.//li')forelementinelements:print(element.text)assertlen(elements)>0assertlen(svg_elements)>1driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')dropdown=driver.find_element(By.CSS_SELECTOR,'.nav-item.dropdown')dropdown.click()active_element=driver.switch_to.active_elementassertactive_element.get_attribute('href').endswith('#')driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceFindElementsFromElement{classFindElementsFromElement{publicstaticvoidMain(string[]args){IWebDriverdriver=newChromeDriver();try{driver.Navigate().GoToUrl("https://example.com");// Get element with tag name 'div'IWebElementelement=driver.FindElement(By.TagName("div"));// Get all the elements available with tag name 'p'IList<IWebElement>elements=element.FindElements(By.TagName("p"));foreach(IWebElementeinelements){System.Console.WriteLine(e.Text);}}finally{driver.Quit();}}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Element Finders'dolet(:driver){start_session}context'without executing finders',skip:'these are just examples, not actual tests'doit'finds the first matching element'dodriver.find_element(class:'tomatoes')endit'uses a subset of the dom to find an element'dofruits=driver.find_element(id:'fruits')fruits.find_element(class:'tomatoes')endit'uses an optimized locator'dodriver.find_element(css:'#fruits .tomatoes')endit'finds all matching elements'dodriver.find_elements(tag_name:'li')endit'gets an element from a collection'doelements=driver.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'finds element from element'doelement=driver.find_element(:tag_name,'div')elements=element.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
const{Builder,By}=require('selenium-webdriver');(asyncfunctionexample(){letdriver=newBuilder().forBrowser('chrome').build();awaitdriver.get('https://www.example.com');// Get element with tag name 'div'
letelement=driver.findElement(By.css("div"));// Get all the elements available with tag name 'p'
letelements=awaitelement.findElements(By.css("p"));for(leteofelements){console.log(awaite.getText());}})();
importorg.openqa.selenium.Byimportorg.openqa.selenium.chrome.ChromeDriverfunmain(){valdriver=ChromeDriver()try{driver.get("https://example.com")// Get element with tag name 'div'
valelement=driver.findElement(By.tagName("div"))// Get all the elements available with tag name 'p'
valelements=element.findElements(By.tagName("p"))for(einelements){println(e.text)}}finally{driver.quit()}}
Get Active Element
It is used to track (or) find DOM element which has the focus in the current browsing context.
importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;publicclassactiveElementTest{publicstaticvoidmain(String[]args){WebDriverdriver=newChromeDriver();try{driver.get("http://www.google.com");driver.findElement(By.cssSelector("[name='q']")).sendKeys("webElement");// Get attribute of current active elementStringattr=driver.switchTo().activeElement().getAttribute("title");System.out.println(attr);}finally{driver.quit();}}}
fromseleniumimportwebdriverfromselenium.webdriver.common.byimportBydeftest_basic_finders():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')body_on_page=driver.find_element(By.CLASS_NAME,'td-home')container_on_page=body_on_page.find_element(By.CLASS_NAME,'container-fluid')assertcontainer_on_page.is_displayed()driver.quit()deftest_evaluating_shadow_DOM():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')custom_element=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_dom_input=custom_element.shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertcustom_element.is_displayed()assertcustom_element.shadow_rootassertshadow_dom_input.is_displayed()driver.quit()deftest_optimized_locator():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')nested_element=driver.find_element(By.CSS_SELECTOR,'.td-home #announcement-banner')assertnested_element.is_displayed()driver.quit()deftest_all_matching_elements():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')header_two_elements=driver.find_elements(By.TAG_NAME,'h2')assertlen(header_two_elements)>1forheader_elementinheader_two_elements:print(header_element.text)driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')main_element=driver.find_element(By.TAG_NAME,'main')svg_elements=main_element.find_elements(By.TAG_NAME,'svg')forsvg_elementinsvg_elements:print(svg_element.is_displayed())## get elements from parent element using XPATH## NOTE: in order to utilize XPATH from current element, you must add "." to beginning of pathheader_tag=driver.find_element(By.TAG_NAME,'header')# Get first element of tag 'ul'ul_tag=header_tag.find_element(By.XPATH,'//ul')# get children of tag 'ul' with tag 'li'elements=ul_tag.find_elements(By.XPATH,'.//li')forelementinelements:print(element.text)assertlen(elements)>0assertlen(svg_elements)>1driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/')dropdown=driver.find_element(By.CSS_SELECTOR,'.nav-item.dropdown')dropdown.click()active_element=driver.switch_to.active_elementassertactive_element.get_attribute('href').endswith('#')driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceActiveElement{classActiveElement{publicstaticvoidMain(string[]args){IWebDriverdriver=newChromeDriver();try{// Navigate to Urldriver.Navigate().GoToUrl("https://www.google.com");driver.FindElement(By.CssSelector("[name='q']")).SendKeys("webElement");// Get attribute of current active elementstringattr=driver.SwitchTo().ActiveElement().GetAttribute("title");System.Console.WriteLine(attr);}finally{driver.Quit();}}}}
# frozen_string_literal: truerequire'spec_helper'RSpec.describe'Element Finders'dolet(:driver){start_session}context'without executing finders',skip:'these are just examples, not actual tests'doit'finds the first matching element'dodriver.find_element(class:'tomatoes')endit'uses a subset of the dom to find an element'dofruits=driver.find_element(id:'fruits')fruits.find_element(class:'tomatoes')endit'uses an optimized locator'dodriver.find_element(css:'#fruits .tomatoes')endit'finds all matching elements'dodriver.find_elements(tag_name:'li')endit'gets an element from a collection'doelements=driver.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'finds element from element'doelement=driver.find_element(:tag_name,'div')elements=element.find_elements(:tag_name,'p')elements.each{|e|putse.text}endit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
const{Builder,By}=require('selenium-webdriver');(asyncfunctionexample(){letdriver=awaitnewBuilder().forBrowser('chrome').build();awaitdriver.get('https://www.google.com');awaitdriver.findElement(By.css('[name="q"]')).sendKeys("webElement");// Get attribute of current active element
letattr=awaitdriver.switchTo().activeElement().getAttribute("title");console.log(`${attr}`)})();
importorg.openqa.selenium.Byimportorg.openqa.selenium.chrome.ChromeDriverfunmain(){valdriver=ChromeDriver()try{driver.get("https://www.google.com")driver.findElement(By.cssSelector("[name='q']")).sendKeys("webElement")// Get attribute of current active element
valattr=driver.switchTo().activeElement().getAttribute("title")print(attr)}finally{driver.quit()}}