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

Finding elements by tag name

Selenium WebDriver's By class provides a tagName() method to find elements by their HTML tag name. This is similar to the getElementsByTagName() DOM method in JavaScript.

This is used when you want to locate elements using their tag name, for example, locating all <tr> tags in a table.

In this recipe, we will briefly see how to use the tagName() locator method.

How to do it...

Let's assume you have a single button element on a page. You can locate this button by using its tag in the following way:

WebElement loginButton = driver.findElement(By.tagName("button"));
loginButton.click();

Take another example where we want to count how many rows are displayed in <table>. We can do this in the following way:

WebElement table = driver.findElement(By.id("summaryTable"));
List<WebElement> rows = table.findElements(By.tagName("tr"));
assertEquals(10, rows.size());

How it works...

The tagName() locator method queries the DOM and returns a list of matching elements for the specified tag name. This method may not be reliable while locating individual elements and the page might have multiple instances of these elements.

See also

  • The Finding elements using findElements method recipe
主站蜘蛛池模板: 宝山区| 壶关县| 长沙市| 南溪县| 丹江口市| 蚌埠市| 杭锦旗| 大埔县| 无棣县| 河间市| 轮台县| 孙吴县| 辽阳市| 三门县| 金平| 泊头市| 长沙县| 北海市| 琼中| 桦甸市| 霞浦县| 河源市| 威远县| 防城港市| 吴忠市| 外汇| 尼勒克县| 疏附县| 兴化市| 来安县| 托克逊县| 咸宁市| 牙克石市| 错那县| 漳州市| 红桥区| 杭州市| 黄龙县| 玉环县| 奉贤区| 盐山县|