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

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
...
主站蜘蛛池模板: 阿尔山市| 海阳市| 石景山区| 赤水市| 昌都县| 曲沃县| 搜索| 白水县| 乃东县| 祁东县| 四会市| 靖江市| 瓦房店市| 侯马市| 望都县| 年辖:市辖区| 崇文区| 靖江市| 吴忠市| 新宁县| 南宫市| 兴文县| 开鲁县| 临颍县| 镇远县| 平遥县| 庆云县| 咸阳市| 长武县| 屏东市| 鄄城县| 景洪市| 荣成市| 民县| 开化县| 兰溪市| 和林格尔县| 宜州市| 水城县| 黄梅县| 连江县|