When and how I can locate element by Tagname using

2020-06-13 02:18发布

I have used most of the element locator while Testing with selenium but very low frequently used 'TagName' locator. Please give and example.

4条回答
走好不送
2楼-- · 2020-06-13 02:53

Now supposing, software web element do not have any ID or Class Name then how to locate that element in selenium WebDriver ? Answer is there are many alternatives of selenium WebDriver element locators and one of them is Locating Element By Tag Name.

Locating 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 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 element by tagName and store its text in variable dropdown.
 String dropdown = driver.findElement(By.tagName("select")).getText();
查看更多
趁早两清
3楼-- · 2020-06-13 02:57

Also importantly, The tagName locating strategy can be used to get or fetch all the links in 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());
查看更多
贼婆χ
4楼-- · 2020-06-13 02:58

we use the actual name of the tag like for anchor and for table and input for . This helps to get all the elements with a given tag name. Example: to select first element of given input

var dialog = driver.FindElement(By.ClassName("ladialog"));
var save = dialog.FindElements(By.TagName("input"))[0];
save.Click();
查看更多
放我归山
5楼-- · 2020-06-13 03:12

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

String dropdown = driver.findElement(By.css("select")).getText();
查看更多
登录 后发表回答