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

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.

主站蜘蛛池模板: 秦安县| 保亭| 宣城市| 行唐县| 松原市| 上杭县| 百色市| 大石桥市| 孝义市| 广饶县| 铜山县| 工布江达县| 台东县| 什邡市| 松滋市| 大城县| 清镇市| 新安县| 贡觉县| 滨州市| 乌鲁木齐市| 丰宁| 大连市| 佛冈县| 阳春市| 通渭县| 龙山县| 玛曲县| 玉树县| 五河县| 平远县| 忻城县| 治县。| 连平县| 辽阳市| 景洪市| 文山县| 安泽县| 莲花县| 青川县| 阿拉善盟|