Locate elements By Tagname in Selenium Webdriver
Overview
In this tutorial, we will learn how to locate elements using By Tagname in Selenium Webdriver automation scripts. Using TagName is very generic and may result in one or more web elements for a particular tag. Example use case where this method is useful, is when we want to count rows in a table using tag <tr>.
Example:
List<WebElement> rows = htmlTable.findElements(By.tagName(“tr”));
For example, if we are testing the number of rows than we can assert with rows.size()
Sample Test to Count <input> tags
In this example, we will count the number of input tag elements on the TestLink Login page.
package com.testingdocs.tests; //Selenium Tutorials - www.TestingDocs.com import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.openqa.selenium.By; import java.net.MalformedURLException; import java.net.URL; import java.util.List; import java.util.concurrent.TimeUnit; public class FindByTagNameExample { public WebDriver driver; @BeforeClass public void setUp() throws MalformedURLException { DesiredCapabilities dCaps = new DesiredCapabilities(); dCaps.setBrowserName("chrome"); driver = new RemoteWebDriver(new URL("http://localhost:4444/wd/hub"), dCaps); } @Test public void testTagNameLocator() throws InterruptedException { driver.navigate() .to("http://localhost/testlink/login.php"); driver.manage().window().maximize(); try { List tags = driver .findElements(By.tagName("input")); driver.manage().timeouts() .implicitlyWait(60, TimeUnit.SECONDS); System.out.println("Number of Input Tags on the Page are: "+ tags.size()); } catch (Exception e) { System.out.println(e.getMessage()); } } @AfterClass public void tearDown() { if (driver != null) { driver.quit(); } } }
—
Selenium Tutorials on this website:
https://www.testingdocs.com/selenium-webdriver-tutorial/
Official Website: