- Selenium WebDriver 3 Practical Guide
- Unmesh Gundecha Satya Avasarala
- 320字
- 2021-08-13 16:08:09
The getAttribute() method
The getAttribute method can be executed on all the WebElements. Remember, we have seen attributes of WebElement in the WebElements section. The HTML attributes are modifiers of HTML elements. They are generally key-value pairs that appear in the start tag of an element. For example:
<label name="Username" id="uname">Enter Username: </label>
In the preceding code, name and id are the attributes or attribute keys and Username and uname are the attribute values.
The API syntax of the getAttribute() method is as follows:
java.lang.String getAttribute(java.lang.String name)
In the preceding code, the input parameter is String, which is the name of the attribute. The return type is again String, which is the value of the attribute.
Now let's see how we can get all the attributes of a WebElement using WebDriver. Here, we will make use of the Search box from the example application. This is what the element looks like:
<input id="search" type="search" name="q" value="" class="input-text required-entry" maxlength="128" placeholder="Search entire store here..." autocomplete="off">
We will list all the attributes of this WebElement using WebDriver. The code for that is as follows:
@Test
public void elementGetAttributesExample() {
WebElement searchBox = driver.findElement(By.name("q"));
System.out.println("Name of the box is: "
+ searchBox.getAttribute("name"));
System.out.println("Id of the box is: " + searchBox.getAttribute("id"));
System.out.println("Class of the box is: "
+ searchBox.getAttribute("class"));
System.out.println("Placeholder of the box is: "
+ searchBox.getAttribute("placeholder"));
}
In the preceding code, the last four lines of code use the getAttribute() method to fetch the attribute values of the name, id, class, and placeholder attributes of the WebElement search box. The output of the preceding code will be following:
Name of the box is: q
Id of the box is: search
Class of the box is: input-text required-entry
Placeholder of the box is: Search entire store here...
Going back to the By.tagName() method of the previous section, if the search by a locating mechanism, By.tagName, results in more than one result, you can use the getAttribute() method to further filter the results and get to your exact intended element.
- 物聯網標準化指南
- CorelDRAW X6 中文版圖形設計實戰從入門到精通
- 物聯網安全:理論、實踐與創新
- Wireshark網絡分析就這么簡單
- 物聯網之霧:基于霧計算的智能硬件快速反應與安全控制
- 2小時讀懂物聯網
- 通信原理及MATLAB/Simulink仿真
- 紅藍攻防:構建實戰化網絡安全防御體系
- Microsoft Power Platform Enterprise Architecture
- INSTANT LinkedIn Customization How-to
- 5G時代的大數據技術架構和關鍵技術詳解
- 計算機網絡技術
- 工業以太網技術:AFDX/TTE網絡原理、接口、互連與安全
- Next.js Quick Start Guide
- 一本書讀懂24種互聯網思維