How To Locate Element By Tag Name Locator In Selenium
In the previous post we have seen “locators in Selenium“. In this post, we discuss “How To Locate Element By Tag Name Locator”. Find the below links on How to find elements on a web page using different types of locators.
1. “How To Locate Element By ID Locator”
2. “How To Locate Element By Name Locator”
3. “How To Locate Element By Class Name Locator”
4. “How To Locate Element By Link Text/Partial Link Text Locator”
5. “How To Locate Element By CSS Selector Locator”
6. “How To Locate Element By XPath Locator”
Coming to the actual post “How To Locate Element By Tag Name Locator”.
Tag Name Locator:
Tag Name locator is used to find the elements matching the specified Tag Name. It is very helpful when we want to extract the content within a Tag.
Syntax:
findElement(By.tagName("HTML Tag Name"))
Script Explanation:
Copy the below mentioned script and execute in your system. It executes as mentioned below:
- Opens Firefox Browser
- Navigates to Google.com
- Here we used, tagName(“a”) to get the links and used findElements method to store the list of all links on the google.com page
- Prints the size of total no. of links
- Print s the list of all the links available on the page
Value to be added in the By.tagName method:
By.tagName("a")
Script:
package seleniumTutorial; import java.util.List; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; public class Locators { public static void main (String [] args){ WebDriver driver = new FirefoxDriver(); driver.get("http://www.google.com"); List <WebElement> list = driver.findElements(By.tagName("a")); System.out.println("Number of links: "+list.size()); for(int i = 0; i < list.size(); i++){ System.out.println(list.get(i).getText()); } } }
Very clear explanation