When and how can I locate an element by tag name using Selenium WebDriver? Please explain with an example
Asked Answered
M

4

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.

Magdaleno answered 6/12, 2015 at 9:17 Comment(1)
is this language dependent? you have no language tag in your questionInaction
J
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();
Julianejuliann answered 6/12, 2015 at 9:35 Comment(1)
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.Conwell
C
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();
Corr answered 18/12, 2018 at 15:35 Comment(2)
What programming language? Java?Itagaki
Is it actually By.css? Not By.CssSelector?Itagaki
S
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();
Swiger answered 23/6, 2017 at 20:16 Comment(2)
Tagname is showing up as deprecated in the JS versionCorr
seleniumhq.github.io/selenium/docs/api/javascript/module/…Corr
H
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());
Hinson answered 19/9, 2017 at 7:57 Comment(1)
What programming language? Java?Itagaki

© 2022 - 2024 — McMap. All rights reserved.