- Selenium WebDriver 3 Practical Guide
- Unmesh Gundecha Satya Avasarala
- 195字
- 2021-08-13 16:08:08
The By.cssSelector() method
The By.cssSelector() method is similar to the By.xpath() method in its usage, but the difference is that it is slightly faster than the By.xpath locating mechanism. The following are the commonly used syntaxes to identify elements:
- To identify an element using the div element with the #flrs ID, we use the #flrs syntax
- To identify the child anchor element, we use the #flrs > a syntax, which will return the link element
- To identify the anchor element with its attribute, we use the #flrs > a[a[href="/intl/en/about.html"]] syntax
Let's try to modify the previous code, which uses the XPath locating mechanism to use the cssSelector mechanism:
@Test
public void byCssSelectorLocatorExample() {
WebElement searchBox =
driver.findElement(By.cssSelector("#search"));
searchBox.sendKeys("Bags");
searchBox.submit();
assertThat(driver.getTitle())
.isEqualTo("Search results for: 'Bags'");
}
The preceding code uses the By.cssSelector locating mechanism, which uses the css selector ID of the Search box.
Let's look at a slightly complex example. We will try to identify the About Us on the Homepage:
@Test
public void byCssSelectorLocatorComplexExample() {
WebElement aboutUs =
driver.findElement(By
.cssSelector("a[href*='/about-magento-demo-store/']"));
aboutUs.click();
assertThat(driver.getTitle())
.isEqualTo("About Us");
}
The preceding code uses the cssSelector() method to find the anchor element identified by its href attribute.
推薦閱讀
- Web安全防護指南:基礎篇
- FreeSWITCH 1.2
- 解析QUIC/HTTP3:未來互聯網的基石
- 數據通信網絡實踐:基礎知識與交換機技術
- 物聯網安全(原書第2版)
- GPS/GNSS原理與應用(第3版)
- 無人機通信
- 物聯網安全技術
- Bonita Open Solution 5.x Essentials
- 互聯網+思維與創新:通往未來的+號
- Building RESTful Web Services with .NET Core
- Enterprise ApplicationDevelopment with Ext JSand Spring
- ReasonML Quick Start Guide
- 網絡基本通信約束下的系統性能極限分析與設計
- 現場總線與工業以太網及其應用技術(第2版)