9

I have used most of the element locators while testing with Selenium, but very low frequently used the 'TagName' locator. Please give an example.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Santosh
  • 101
  • 1
  • 1
  • 3

4 Answers4

11

Now supposing, a software web element does not have any ID or Class Name, then how can we locate that element in Selenium WebDriver? The answer is there are many alternatives of the Selenium WebDriver element locators and one of them is locating an element by tag name.

Locating an element by tag name is not too much popular because in most of cases, we will have other alternatives of element locators. But yes, if there is not any alternative then you can use the element's DOM tag name to locate that element in webdriver.

Enter image description here

Here you can select the tagname as a locator like:

// Locating the element by tagName and store its text in variable 'dropdown'.
String dropdown = driver.findElement(By.tagName("select")).getText();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Shah
  • 413
  • 2
  • 11
  • Using it to find an `IFRAME` or maybe `A` tags to get all the links on the page are more likely to be more widely used. – JeffC Dec 06 '15 at 14:56
4

Thanks to the deprecation of By.tagName you should use By.css for Shah's answer...

String dropdown = driver.findElement(By.css("select")).getText();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JGleason
  • 3,067
  • 6
  • 20
  • 54
3

We use the actual name of the tag like <a> for anchor and <table> for table and input for <input>. This helps to get all the elements with a given tag name.

Example: to select the first element of a given input

var dialog = driver.FindElement(By.ClassName("ladialog"));
var save = dialog.FindElements(By.TagName("input"))[0];
save.Click();
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dawit Reda
  • 33
  • 5
0

Also importantly, the tagName locating strategy can be used to get or fetch all the links on a webpage and print them to console. Try this:

// Get all links in a webpage
List<WebElement> allLinks = driver.findElements(By.tagName("a"));
System.out.println("Links count is: " + allLinks.size());

for(WebElement link : allLinks)
    System.out.println(link.getText());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131