- 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
...
- C++黑客編程揭秘與防范
- 智能網聯汽車V2X與智能網聯設施I2X
- 工業控制網絡安全技術與實踐
- 新一代物聯網架構技術:分層算力網絡
- Building RESTful Web Services with Spring 5(Second Edition)
- 數字通信同步技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- The Kubernetes Workshop
- 物聯網與智能家居
- 互聯網安全的40個智慧洞見(2016)
- LwIP應用開發實戰指南:基于STM32
- 精通SEO:100%網站流量提升密碼
- Migrating to Drupal7
- 物聯網傳感器技術與應用
- 物聯網系統設計
- Alfresco Share