- Selenium WebDriver 3 Practical Guide
- Unmesh Gundecha Satya Avasarala
- 207字
- 2021-08-13 16:08:05
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.
- Application Development with Qt Creator(Second Edition)
- FreeSWITCH 1.2
- MERN Quick Start Guide
- Hands-On Chatbots and Conversational UI Development
- OpenLayers Cookbook
- JBoss EAP6 High Availability
- WordPress 5 Complete
- 互聯網安全的40個智慧洞見:2015年中國互聯網安全大會文集
- The Kubernetes Workshop
- 互聯網+思維與創新:通往未來的+號
- 從實踐中學習手機抓包與數據分析
- 中國互聯網發展報告2021
- 園區網絡架構與技術
- bash網絡安全運維
- SRv6網絡部署指南