Extracting WebElements dynamically using tagName

Now that we have seen how to create relative (customized) XPaths, it's time to see how to retrieve WebElements programmatically using Java lists. The best way to understand this is through an example. Suppose we want to find all the input textboxes on the login page of http://www.freecrm.com. We will make use of the findElements method. Remember, the findElements method is in the SearchContext interface.

Since the WebDriver interface is a child interface of SearchContext, it inherits the findElements method and we can invoke this method on the reference variable of WebDriver. In conjunction with findElements, we will also make use of the static method, tagName , of the By class.

The following code makes efficient use of the list interface in Java (present in the Java.Util package): 

public class URLTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\SeleniumWD\src\main\resources\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.freecrm.com");
List<WebElement> inputBoxes =
driver.findElements(By.tagName("input"));
System.out.println("No of inputBoxes: " + inputBoxes.size());
}
}

Output from this program:
No of inputBoxes: 3

The two textboxes for UserName and Password and the Login button are treated as input tags. The tagName static method is an extremely useful method and you can use this method for almost any element on any web page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset