Localizando elementos com base nos valores providenciados pelo localizador.
Um dos aspectos mais fundamentais do uso do Selenium é obter referências de elementos para trabalhar.
O Selenium oferece várias estratégias de localizador para identificar exclusivamente um elemento.
Há muitas maneiras de usar os localizadores em cenários complexos. Para os propósitos desta documentação,
use a página de teste de localizadores do Selenium.
Primeiro Elemento correspondente
Muitos localizadores irão corresponder a vários elementos na página.
O método de elemento de localização singular retornará uma referência ao
primeiro elemento encontrado dentro de um determinado contexto.
Avaliando o DOM inteiro
Quando o metodo find element é chamado na instância do driver, ele
retorna uma referência ao primeiro elemento no DOM que corresponde ao localizador fornecido.
Esse valor pode ser guardado e usado para ações futuras do elemento. Na página de teste de localizadores do Selenium, existem
dois elementos com o nome de classe information, então este método retorna o primeiro campo de texto.
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# The tests below marked as skipped mirror the HTML snippet shown at the top of the# "Finding web elements" documentation and are illustrative only, matching how the# same examples are shown for the other language bindings:## <ol id="vegetables"># <li class="potatoes">…# <li class="onions">…# <li class="tomatoes"><span>Tomato is a Vegetable</span>…# </ol># <ul id="fruits"># <li class="bananas">…# <li class="apples">…# <li class="tomatoes"><span>Tomato is a Fruit</span>…# </ul>@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_basic_finders(driver):vegetable=driver.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_subset_of_dom(driver):fruits=driver.find_element(By.ID,'fruits')fruit=fruits.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_optimized_locator(driver):fruit=driver.find_element(By.CSS_SELECTOR,'#fruits .tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_all_matching_elements(driver):plants=driver.find_elements(By.TAG_NAME,'li')deftest_evaluating_shadow_dom():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')shadow_host=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_root=shadow_host.shadow_rootassertshadow_rootshadow_content=shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertshadow_host.is_displayed()assertshadow_content.is_displayed()driver.quit()deftest_get_element():driver=webdriver.Chrome()driver.get('https://www.example.com')elements=driver.find_elements(By.TAG_NAME,'p')forelementinelements:print(element.text)assertlen(elements)>0driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.example.com')element=driver.find_element(By.TAG_NAME,'div')elements=element.find_elements(By.TAG_NAME,'p')foreinelements:print(e.text)assertlen(elements)>0driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/selenium/web/web-form.html')driver.find_element(By.CSS_SELECTOR,'[name="my-text"]').send_keys('webElement')attr=driver.switch_to.active_element.get_attribute('name')assertattr=='my-text'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')end# rubocop:disable RSpec/Outputit'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}end# rubocop:enable RSpec/Outputit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# The tests below marked as skipped mirror the HTML snippet shown at the top of the# "Finding web elements" documentation and are illustrative only, matching how the# same examples are shown for the other language bindings:## <ol id="vegetables"># <li class="potatoes">…# <li class="onions">…# <li class="tomatoes"><span>Tomato is a Vegetable</span>…# </ol># <ul id="fruits"># <li class="bananas">…# <li class="apples">…# <li class="tomatoes"><span>Tomato is a Fruit</span>…# </ul>@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_basic_finders(driver):vegetable=driver.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_subset_of_dom(driver):fruits=driver.find_element(By.ID,'fruits')fruit=fruits.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_optimized_locator(driver):fruit=driver.find_element(By.CSS_SELECTOR,'#fruits .tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_all_matching_elements(driver):plants=driver.find_elements(By.TAG_NAME,'li')deftest_evaluating_shadow_dom():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')shadow_host=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_root=shadow_host.shadow_rootassertshadow_rootshadow_content=shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertshadow_host.is_displayed()assertshadow_content.is_displayed()driver.quit()deftest_get_element():driver=webdriver.Chrome()driver.get('https://www.example.com')elements=driver.find_elements(By.TAG_NAME,'p')forelementinelements:print(element.text)assertlen(elements)>0driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.example.com')element=driver.find_element(By.TAG_NAME,'div')elements=element.find_elements(By.TAG_NAME,'p')foreinelements:print(e.text)assertlen(elements)>0driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/selenium/web/web-form.html')driver.find_element(By.CSS_SELECTOR,'[name="my-text"]').send_keys('webElement')attr=driver.switch_to.active_element.get_attribute('name')assertattr=='my-text'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')end# rubocop:disable RSpec/Outputit'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}end# rubocop:enable RSpec/Outputit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
Java e C# As classes WebDriver, WebElement e ShadowRoot todas implementam o SearchContext interface, que é
considerada uma role-based interface(interface baseada em função). As interfaces baseadas em função permitem determinar se uma determinada
implementação de driver suporta um recurso específico. Essas interfaces são claramente definidas e tentam
aderir a ter apenas um único papel de responsabilidade.
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.
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# The tests below marked as skipped mirror the HTML snippet shown at the top of the# "Finding web elements" documentation and are illustrative only, matching how the# same examples are shown for the other language bindings:## <ol id="vegetables"># <li class="potatoes">…# <li class="onions">…# <li class="tomatoes"><span>Tomato is a Vegetable</span>…# </ol># <ul id="fruits"># <li class="bananas">…# <li class="apples">…# <li class="tomatoes"><span>Tomato is a Fruit</span>…# </ul>@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_basic_finders(driver):vegetable=driver.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_subset_of_dom(driver):fruits=driver.find_element(By.ID,'fruits')fruit=fruits.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_optimized_locator(driver):fruit=driver.find_element(By.CSS_SELECTOR,'#fruits .tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_all_matching_elements(driver):plants=driver.find_elements(By.TAG_NAME,'li')deftest_evaluating_shadow_dom():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')shadow_host=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_root=shadow_host.shadow_rootassertshadow_rootshadow_content=shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertshadow_host.is_displayed()assertshadow_content.is_displayed()driver.quit()deftest_get_element():driver=webdriver.Chrome()driver.get('https://www.example.com')elements=driver.find_elements(By.TAG_NAME,'p')forelementinelements:print(element.text)assertlen(elements)>0driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.example.com')element=driver.find_element(By.TAG_NAME,'div')elements=element.find_elements(By.TAG_NAME,'p')foreinelements:print(e.text)assertlen(elements)>0driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/selenium/web/web-form.html')driver.find_element(By.CSS_SELECTOR,'[name="my-text"]').send_keys('webElement')attr=driver.switch_to.active_element.get_attribute('name')assertattr=='my-text'driver.quit()
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# The tests below marked as skipped mirror the HTML snippet shown at the top of the# "Finding web elements" documentation and are illustrative only, matching how the# same examples are shown for the other language bindings:## <ol id="vegetables"># <li class="potatoes">…# <li class="onions">…# <li class="tomatoes"><span>Tomato is a Vegetable</span>…# </ol># <ul id="fruits"># <li class="bananas">…# <li class="apples">…# <li class="tomatoes"><span>Tomato is a Fruit</span>…# </ul>@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_basic_finders(driver):vegetable=driver.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_subset_of_dom(driver):fruits=driver.find_element(By.ID,'fruits')fruit=fruits.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_optimized_locator(driver):fruit=driver.find_element(By.CSS_SELECTOR,'#fruits .tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_all_matching_elements(driver):plants=driver.find_elements(By.TAG_NAME,'li')deftest_evaluating_shadow_dom():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')shadow_host=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_root=shadow_host.shadow_rootassertshadow_rootshadow_content=shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertshadow_host.is_displayed()assertshadow_content.is_displayed()driver.quit()deftest_get_element():driver=webdriver.Chrome()driver.get('https://www.example.com')elements=driver.find_elements(By.TAG_NAME,'p')forelementinelements:print(element.text)assertlen(elements)>0driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.example.com')element=driver.find_element(By.TAG_NAME,'div')elements=element.find_elements(By.TAG_NAME,'p')foreinelements:print(e.text)assertlen(elements)>0driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/selenium/web/web-form.html')driver.find_element(By.CSS_SELECTOR,'[name="my-text"]').send_keys('webElement')attr=driver.switch_to.active_element.get_attribute('name')assertattr=='my-text'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')end# rubocop:disable RSpec/Outputit'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}end# rubocop:enable RSpec/Outputit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
Existem vários casos de uso para a necessidade de obter referências a todos os elementos que correspondem a um localizador, em vez
do que apenas o primeiro. Os métodos plurais find elements retornam uma coleção de referências de elementos.
Se não houver correspondências, uma lista vazia será retornada. Nesse caso,
referências a todos os elementos input serão devolvidas em uma coleção.
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# The tests below marked as skipped mirror the HTML snippet shown at the top of the# "Finding web elements" documentation and are illustrative only, matching how the# same examples are shown for the other language bindings:## <ol id="vegetables"># <li class="potatoes">…# <li class="onions">…# <li class="tomatoes"><span>Tomato is a Vegetable</span>…# </ol># <ul id="fruits"># <li class="bananas">…# <li class="apples">…# <li class="tomatoes"><span>Tomato is a Fruit</span>…# </ul>@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_basic_finders(driver):vegetable=driver.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_subset_of_dom(driver):fruits=driver.find_element(By.ID,'fruits')fruit=fruits.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_optimized_locator(driver):fruit=driver.find_element(By.CSS_SELECTOR,'#fruits .tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_all_matching_elements(driver):plants=driver.find_elements(By.TAG_NAME,'li')deftest_evaluating_shadow_dom():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')shadow_host=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_root=shadow_host.shadow_rootassertshadow_rootshadow_content=shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertshadow_host.is_displayed()assertshadow_content.is_displayed()driver.quit()deftest_get_element():driver=webdriver.Chrome()driver.get('https://www.example.com')elements=driver.find_elements(By.TAG_NAME,'p')forelementinelements:print(element.text)assertlen(elements)>0driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.example.com')element=driver.find_element(By.TAG_NAME,'div')elements=element.find_elements(By.TAG_NAME,'p')foreinelements:print(e.text)assertlen(elements)>0driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/selenium/web/web-form.html')driver.find_element(By.CSS_SELECTOR,'[name="my-text"]').send_keys('webElement')attr=driver.switch_to.active_element.get_attribute('name')assertattr=='my-text'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')end# rubocop:disable RSpec/Outputit'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}end# rubocop:enable RSpec/Outputit'find active element'dodriver.find_element(css:'[name="q"]').send_keys('webElement')driver.switch_to.active_element.attribute('title')endendend
Muitas vezes você obterá uma coleção de elementos, mas quer trabalhar apenas com um elemento específico, o que significa que você
precisa iterar sobre a coleção e identificar o que você deseja.
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# The tests below marked as skipped mirror the HTML snippet shown at the top of the# "Finding web elements" documentation and are illustrative only, matching how the# same examples are shown for the other language bindings:## <ol id="vegetables"># <li class="potatoes">…# <li class="onions">…# <li class="tomatoes"><span>Tomato is a Vegetable</span>…# </ol># <ul id="fruits"># <li class="bananas">…# <li class="apples">…# <li class="tomatoes"><span>Tomato is a Fruit</span>…# </ul>@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_basic_finders(driver):vegetable=driver.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_subset_of_dom(driver):fruits=driver.find_element(By.ID,'fruits')fruit=fruits.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_optimized_locator(driver):fruit=driver.find_element(By.CSS_SELECTOR,'#fruits .tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_all_matching_elements(driver):plants=driver.find_elements(By.TAG_NAME,'li')deftest_evaluating_shadow_dom():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')shadow_host=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_root=shadow_host.shadow_rootassertshadow_rootshadow_content=shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertshadow_host.is_displayed()assertshadow_content.is_displayed()driver.quit()deftest_get_element():driver=webdriver.Chrome()driver.get('https://www.example.com')elements=driver.find_elements(By.TAG_NAME,'p')forelementinelements:print(element.text)assertlen(elements)>0driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.example.com')element=driver.find_element(By.TAG_NAME,'div')elements=element.find_elements(By.TAG_NAME,'p')foreinelements:print(e.text)assertlen(elements)>0driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/selenium/web/web-form.html')driver.find_element(By.CSS_SELECTOR,'[name="my-text"]').send_keys('webElement')attr=driver.switch_to.active_element.get_attribute('name')assertattr=='my-text'driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Firefox;usingSystem.Collections.Generic;namespaceFindElementsExample{classFindElementsExample{publicstaticvoidMain(string[]args){IWebDriverdriver=newFirefoxDriver();try{// Navegar até a URLdriver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");// Obtém todos os elementos disponiveis com o nome da tag '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')end# rubocop:disable RSpec/Outputit'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}end# rubocop:enable RSpec/Outputit'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{// Navegar até a URL
awaitdriver.get('https://www.selenium.dev/selenium/web/locators_tests/locators.html');// Obtém todos os elementos disponiveis com o nome da 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://www.selenium.dev/selenium/web/locators_tests/locators.html")// Obtém todos os elementos disponiveis com o nome da tag 'p'
valelements=driver.findElements(By.tagName("p"))for(elementinelements){println("Paragraph text:"+element.text)}}finally{driver.quit()}}
Localizar Elementos em um Elemento
Ele é usado para localizar a lista de WebElements filhos correspondentes dentro do contexto do elemento pai.
Para realizar isso, o WebElement pai é encadeado com o ‘findElements’ para acessar seus elementos filhos.
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://www.selenium.dev/selenium/web/locators_tests/locators.html");// Obtém o elemento formWebElementelement=driver.findElement(By.tagName("form"));// Obtém todos os elementos input dentro do formList<WebElement>elements=element.findElements(By.tagName("input"));for(WebElemente:elements){System.out.println(e.getAttribute("value"));}}finally{driver.quit();}}}
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# The tests below marked as skipped mirror the HTML snippet shown at the top of the# "Finding web elements" documentation and are illustrative only, matching how the# same examples are shown for the other language bindings:## <ol id="vegetables"># <li class="potatoes">…# <li class="onions">…# <li class="tomatoes"><span>Tomato is a Vegetable</span>…# </ol># <ul id="fruits"># <li class="bananas">…# <li class="apples">…# <li class="tomatoes"><span>Tomato is a Fruit</span>…# </ul>@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_basic_finders(driver):vegetable=driver.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_subset_of_dom(driver):fruits=driver.find_element(By.ID,'fruits')fruit=fruits.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_optimized_locator(driver):fruit=driver.find_element(By.CSS_SELECTOR,'#fruits .tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_all_matching_elements(driver):plants=driver.find_elements(By.TAG_NAME,'li')deftest_evaluating_shadow_dom():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')shadow_host=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_root=shadow_host.shadow_rootassertshadow_rootshadow_content=shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertshadow_host.is_displayed()assertshadow_content.is_displayed()driver.quit()deftest_get_element():driver=webdriver.Chrome()driver.get('https://www.example.com')elements=driver.find_elements(By.TAG_NAME,'p')forelementinelements:print(element.text)assertlen(elements)>0driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.example.com')element=driver.find_element(By.TAG_NAME,'div')elements=element.find_elements(By.TAG_NAME,'p')foreinelements:print(e.text)assertlen(elements)>0driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/selenium/web/web-form.html')driver.find_element(By.CSS_SELECTOR,'[name="my-text"]').send_keys('webElement')attr=driver.switch_to.active_element.get_attribute('name')assertattr=='my-text'driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;usingSystem.Collections.Generic;namespaceFindElementsFromElement{classFindElementsFromElement{publicstaticvoidMain(string[]args){IWebDriverdriver=newChromeDriver();try{driver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");// Obtém o elemento formIWebElementelement=driver.FindElement(By.TagName("form"));// Obtém todos os elementos input dentro do formIList<IWebElement>elements=element.FindElements(By.TagName("input"));foreach(IWebElementeinelements){System.Console.WriteLine(e.GetAttribute("value"));}}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')end# rubocop:disable RSpec/Outputit'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}end# rubocop:enable RSpec/Outputit'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.selenium.dev/selenium/web/locators_tests/locators.html');// Obtém o elemento form
letelement=driver.findElement(By.css("form"));// Obtém todos os elementos input dentro do form
letelements=awaitelement.findElements(By.css("input"));for(leteofelements){console.log(awaite.getAttribute("value"));}})();
importorg.openqa.selenium.Byimportorg.openqa.selenium.chrome.ChromeDriverfunmain(){valdriver=ChromeDriver()try{driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")// Obtém o elemento form
valelement=driver.findElement(By.tagName("form"))// Obtém todos os elementos input dentro do form
valelements=element.findElements(By.tagName("input"))for(einelements){println(e.getAttribute("value"))}}finally{driver.quit()}}
Obter elemento ativo
Ele é usado para rastrear (ou) encontrar um elemento DOM que tem o foco no contexto de navegação atual.
importorg.openqa.selenium.*;importorg.openqa.selenium.chrome.ChromeDriver;publicclassactiveElementTest{publicstaticvoidmain(String[]args){WebDriverdriver=newChromeDriver();try{driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html");driver.findElement(By.cssSelector("#fname")).sendKeys("webElement");// Obter atributo do elemento atualmente ativoStringattr=driver.switchTo().activeElement().getAttribute("name");System.out.println(attr);}finally{driver.quit();}}}
importpytestfromseleniumimportwebdriverfromselenium.webdriver.common.byimportBy# The tests below marked as skipped mirror the HTML snippet shown at the top of the# "Finding web elements" documentation and are illustrative only, matching how the# same examples are shown for the other language bindings:## <ol id="vegetables"># <li class="potatoes">…# <li class="onions">…# <li class="tomatoes"><span>Tomato is a Vegetable</span>…# </ol># <ul id="fruits"># <li class="bananas">…# <li class="apples">…# <li class="tomatoes"><span>Tomato is a Fruit</span>…# </ul>@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_basic_finders(driver):vegetable=driver.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_subset_of_dom(driver):fruits=driver.find_element(By.ID,'fruits')fruit=fruits.find_element(By.CLASS_NAME,'tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_optimized_locator(driver):fruit=driver.find_element(By.CSS_SELECTOR,'#fruits .tomatoes')@pytest.mark.skip(reason="illustrative example, not an executable test")deftest_all_matching_elements(driver):plants=driver.find_elements(By.TAG_NAME,'li')deftest_evaluating_shadow_dom():driver=webdriver.Chrome()driver.implicitly_wait(5)driver.get('https://www.selenium.dev/selenium/web/shadowRootPage.html')shadow_host=driver.find_element(By.TAG_NAME,'custom-checkbox-element')shadow_root=shadow_host.shadow_rootassertshadow_rootshadow_content=shadow_root.find_element(By.CSS_SELECTOR,'input[type=checkbox]')assertshadow_host.is_displayed()assertshadow_content.is_displayed()driver.quit()deftest_get_element():driver=webdriver.Chrome()driver.get('https://www.example.com')elements=driver.find_elements(By.TAG_NAME,'p')forelementinelements:print(element.text)assertlen(elements)>0driver.quit()deftest_find_elements_from_element():driver=webdriver.Chrome()driver.get('https://www.example.com')element=driver.find_element(By.TAG_NAME,'div')elements=element.find_elements(By.TAG_NAME,'p')foreinelements:print(e.text)assertlen(elements)>0driver.quit()deftest_get_active_element():driver=webdriver.Chrome()driver.get('https://www.selenium.dev/selenium/web/web-form.html')driver.find_element(By.CSS_SELECTOR,'[name="my-text"]').send_keys('webElement')attr=driver.switch_to.active_element.get_attribute('name')assertattr=='my-text'driver.quit()
usingOpenQA.Selenium;usingOpenQA.Selenium.Chrome;namespaceActiveElement{classActiveElement{publicstaticvoidMain(string[]args){IWebDriverdriver=newChromeDriver();try{// Navegar até a URLdriver.Navigate().GoToUrl("https://www.selenium.dev/selenium/web/locators_tests/locators.html");driver.FindElement(By.CssSelector("#fname")).SendKeys("webElement");// Obter atributo do elemento atualmente ativostringattr=driver.SwitchTo().ActiveElement().GetAttribute("name");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')end# rubocop:disable RSpec/Outputit'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}end# rubocop:enable RSpec/Outputit'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.selenium.dev/selenium/web/locators_tests/locators.html');awaitdriver.findElement(By.css('#fname')).sendKeys("webElement");// Obter atributo do elemento atualmente ativo
letattr=awaitdriver.switchTo().activeElement().getAttribute("name");console.log(`${attr}`)})();
importorg.openqa.selenium.Byimportorg.openqa.selenium.chrome.ChromeDriverfunmain(){valdriver=ChromeDriver()try{driver.get("https://www.selenium.dev/selenium/web/locators_tests/locators.html")driver.findElement(By.cssSelector("#fname")).sendKeys("webElement")// Obter atributo do elemento atualmente ativo
valattr=driver.switchTo().activeElement().getAttribute("name")print(attr)}finally{driver.quit()}}