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

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.

主站蜘蛛池模板: 洪雅县| 丽水市| 高唐县| 浦东新区| 宣汉县| 湖北省| 个旧市| 河曲县| 和平区| 汕尾市| 英德市| 营口市| 高陵县| 平安县| 邵东县| 沂南县| 天镇县| 斗六市| 中卫市| 五指山市| 龙泉市| 开远市| 南靖县| 图木舒克市| 台中市| 明溪县| 南部县| 斗六市| 平度市| 工布江达县| 垣曲县| 东安县| 景宁| 临清市| 虞城县| 岑巩县| 鄯善县| 沙雅县| 和龙市| 滨州市| 中牟县|