- Selenium WebDriver 3 Practical Guide
- Unmesh Gundecha Satya Avasarala
- 234字
- 2021-08-13 16:08:08
The By.tagName() method
Locating an element by tag name is slightly different from the locating mechanisms we saw earlier. For example, on a Homepage, if you search for an element with the button tag name, it will result in multiple WebElements because there are nine buttons present on the Homepage. So, it is always advisable to use the findElements() method rather than the findElement() method when trying to locate elements using tag names.
Let's see how the code looks when a search for the number of links present on a Homepage is made:
@Test
public void byTagNameLocatorExample() {
// get all links from the Home page
List<WebElement> links = driver.findElements(By.tagName("a"));
System.out.println("Found links:" + links.size());
// print links which have text using Java 8 Streams API
links.stream()
.filter(elem -> elem.getText().length() > 0)
.forEach(elem -> System.out.println(elem.getText()));
}
In the preceding code, we have used the By.tagName locating mechanism and the findElements() method, which return a list of all the links, that is, the a anchor tags defined on the page. On line five, we printed the size of the list, and then printed text of only links where the text has been provided. We use the Java 8 Stream API to filter the element list and output the text value by calling the getText() method. This will generate the following output:
Found links:88
ACCOUNT
CART
WOMEN
...
- EJB 3.1從入門到精通
- 解析QUIC/HTTP3:未來互聯網的基石
- 面向物聯網的CC2530與傳感器應用開發
- Building E-commerce Sites with VirtueMart Cookbook
- 智能網聯汽車V2X與智能網聯設施I2X
- 物聯網安全與深度學習技術
- 計算機網絡與數據通信
- 物聯網通信技術
- Mastering TypeScript 3
- Spring 5.0 Projects
- 6G新技術 新網絡 新通信
- WordPress Web Application Development
- Building Web Applications with ArcGIS
- 網絡安全應急響應技術實戰指南
- 異構蜂窩網絡關鍵理論與技術