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

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.

主站蜘蛛池模板: 福清市| 和政县| 日土县| 亳州市| 卢湾区| 岱山县| 新干县| 北海市| 岑溪市| 永安市| 娱乐| 搜索| 夏河县| 易门县| 徐闻县| 湘潭市| 湛江市| 丘北县| 桂林市| 民乐县| 玉山县| 莱西市| 通辽市| 疏勒县| 清原| 黄平县| 忻城县| 怀宁县| 柞水县| 济南市| 商水县| 浪卡子县| 漳平市| 乐都县| 襄樊市| 宜兴市| 阿坝县| 临朐县| 民乐县| 霸州市| 东港市|