The By.tagName() method

Locating an element by tag name is slightly different from the locating mechanisms we saw earlier. For example, on a Homepage, if you search for an element with the button tag name, it will result in multiple WebElements because there are nine buttons present on the Homepage. So, it is always advisable to use the findElements() method rather than the findElement() method when trying to locate elements using tag names.

Let's see how the code looks when a search for the number of links present on a Homepage is made:

@Testpublic void byTagNameLocatorExample() {    // get all links from the Home page    List<WebElement> links = driver.findElements(By.tagName("a"));    System.out.println("Found links:" + links.size());    // print ...

Get Selenium WebDriver 3 Practical Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.