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

The By.id() method

On a web page, each element is uniquely identified by an ID attribute, which is optionally provided. An ID can be assigned manually by the developer of the web application or left to be dynamically generated by the application. Dynamically-generated IDs can be changed on every page refresh or over a period of time. Now, consider the HTML code of the Search box:

<input id="search" type="search" name="q" value="" class="input-text required-entry" maxlength="128" placeholder="Search entire store here..." autocomplete="off">

In the preceding code, the id attribute value of the search box is search.

Let's see how to use the ID attribute as a locating mechanism to find the Search box:

@Test
public void byIdLocatorExample() {
WebElement searchBox = driver.findElement(By.id("search"));
searchBox.sendKeys("Bags");
searchBox.submit();
assertThat(driver.getTitle())
.isEqualTo("Search results for: 'Bags'");
}

In preceding code, we used the By.id() method and the search box's id attribute value to find the element.

Here, try to use the By.id identifier, and use the name value (that is, q) instead of the id value (that is, search). Modify line three as follows:

WebElement searchBox = driver.findElement(By.id("q")); 

The test script will fail to throw an exception, as follows:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to locate element: {"method":"id","selector":"q"}

WebDriver couldn't find an element by id whose value is q. Thus, it throws an exception saying NoSuchElementException.

主站蜘蛛池模板: 酒泉市| 陆川县| 抚顺县| 奈曼旗| 婺源县| 睢宁县| 理塘县| 双辽市| 贞丰县| 南华县| 临猗县| 德令哈市| 贡嘎县| 贞丰县| 黄大仙区| 嵊州市| 鹤山市| 古浪县| 霍林郭勒市| 融水| 铁力市| 南华县| 额济纳旗| 临沧市| 佳木斯市| 永昌县| 油尖旺区| 湟中县| 宁乡县| 咸丰县| 得荣县| 白朗县| 汝阳县| 巴林右旗| 罗甸县| 宣武区| 阳信县| 阳曲县| 黄山市| 克东县| 凯里市|