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

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.

主站蜘蛛池模板: 长海县| 宁安市| 读书| 乌拉特后旗| 诏安县| 昌乐县| 阜城县| 新乡市| 华亭县| 南城县| 延安市| 乌拉特前旗| 扎囊县| 扎赉特旗| 乐昌市| 日土县| 大港区| 土默特左旗| 泰兴市| 百色市| 江川县| 阿拉善右旗| 长宁区| 临邑县| 葫芦岛市| 卢氏县| 观塘区| 石阡县| 大方县| 淮阳县| 新泰市| 杭锦旗| 射洪县| 新密市| 盘山县| 澄江县| 绥化市| 富蕴县| 吴堡县| 湖口县| 平山县|