官术网_书友最值得收藏!

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
...
主站蜘蛛池模板: 泸水县| 延长县| 尼木县| 无棣县| 遂川县| 丰县| 安宁市| 仁怀市| 巩义市| SHOW| 利津县| 石城县| 青冈县| 万山特区| 滨海县| 务川| 菏泽市| 思茅市| 盐边县| 台北市| 东山县| 建水县| 淮北市| 云龙县| 新巴尔虎右旗| 翁源县| 巨鹿县| 甘孜县| 高清| 临漳县| 萍乡市| 信宜市| 普宁市| 千阳县| 石景山区| 叶城县| 乌兰县| 图木舒克市| 台南县| 纳雍县| 黑山县|