How to use findElement() method in Selenium WebDriver

Selenium Webdriver's findElement() method is useful to locate WebElement for page. It is one of the mostly used method in selenium webdriver. It uses By object as parameter can can use it with various element locating strategies like ID, Name, Linktext, Partial Linktext, Tag Name, Class Name, DOM Locator, CSS Selector and Xpath. findElement() will return first matching webelement from page.


Let's look at example which show us exact usage of findElement() method.

How findElement() Method Works?
package TestPack;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

public class testFindElement {

 public static void main(String[] args) throws InterruptedException {
  String exePath = "D:\\chromedriver_win32\\chromedriver.exe";
  System.setProperty("webdriver.chrome.driver", exePath);
  WebDriver driver = new ChromeDriver();
  
  driver.get("http://only-testing-blog.blogspot.com/2015/03/chart.html");
  
  //Find textbox element using findElement and type text in it.
  driver.findElement(By.xpath("//*[@id=\"tooltip-1\"]")).sendKeys("Textbox Element Located successfully.");
 }
}

Result : It will locate webelement textbox using findElement which uses Xpath element locating strategy. And then sendKeys will type text in located textbox element.


When you need findElement()?
You need findElement method whenever you want to interact with any webelement like textbox, button, link, checkbox ect.. 

No comments:

Post a Comment