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

Locating WebElements using WebDriver 

Let's start this section by automating the Search feature from the Homepage of the demo application, http://demo-store.seleniumacademy.com/, which involves navigating to the homepage, typing the search text in the textbox, and executing the search. The code is as follows:

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;

public class SearchTest {

WebDriver driver;

@BeforeMethod
public void setup() {
System.setProperty("webdriver.chrome.driver",
"./src/test/resources/drivers/chromedriver");
driver = new ChromeDriver();
driver.get("http://demo-store.seleniumacademy.com/");
}

@Test
public void searchProduct() {
// find search box and enter search string
WebElement searchBox = driver.findElement(By.name("q"));
searchBox.sendKeys("Phones");
WebElement searchButton =
driver.findElement(By.className("search-button"));
searchButton.click();
assertThat(driver.getTitle())
.isEqualTo("Search results for: 'Phones'");
}

@AfterMethod
public void tearDown() {
driver.quit();
}
}

As you can see, there are three new things that are highlighted, as follows:

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

They are the findElement() method, the By.name() method, and the WebElement interface. The findElement() and By() methods instruct WebDriver to locate a WebElement on a web page, and once found, the findElement() method returns the WebElement instance of that element. Actions, such as click and type, are performed on a returned WebElement using the methods declared in the WebElement interface, which will be discussed in detail in the next section.

主站蜘蛛池模板: 六安市| 遂平县| 铁力市| 宣威市| 武义县| 左贡县| 富民县| 巧家县| 安丘市| 阳城县| 靖边县| 固始县| 财经| 乌兰浩特市| 鄱阳县| 来凤县| 黎川县| 石楼县| 海晏县| 米泉市| 彭山县| 泾川县| 临猗县| 东阿县| 津市市| 富源县| 台东县| 黎城县| 高邮市| 阿城市| 洪江市| 沂南县| 宜君县| 阿克苏市| 铁岭市| 濮阳市| 深圳市| 浮梁县| 上饶县| 湘潭市| 东平县|