findElement() method in selenium
findElement method is one of the most used method in selenium as it is used to fine element like textbox, button, link, dropdown, listbox on webpage. You need to perform actions on different web elements on page and findelement method helps you to find element by given locator strategy.
- findelement() is method of SearchContext interface which is inherited in WebDriver interface.
- findElement method can select max single web element from page.
- When use findElement, It will always select first found element from the page based on given locatory strategy.
- If not found any element on page using findElement() method then it will return NoSuchElementException.
- You can use findElement by id, name, tagName, className, xpath, linkText, partialLinkText and cssSelector.
- Indexing is not required in findElement() method as it will return single element only.
Example of using findElement() in selenium
Below given example will show you how to use findelement() method in selenium.
- Syntax to use findElement method : driver.findelement(By.element_locator)
Selenium findElement() example
package testPackage;import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class FindelementExample { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "D:\\chromedriver.exe"); WebDriver driver=new ChromeDriver(); driver.get("http://only-testing-blog.blogspot.com/2014/02/attributes.html"); //Find textbox element by id and type text in it. driver.findElement(By.id("text1")).sendKeys("First Name"); //Find textbox element by name and type text in it. driver.findElement(By.name("To Hide")).sendKeys("Fill hidden text box"); //Find checkbox element by xpath and select it. driver.findElement(By.xpath("//input[@id='check2']")).click(); //Find checkbox element by css selector and select it. driver.findElement(By.cssSelector("#check3")).click(); } }
In above given example, First findelement method will select first name textbox by id locator and type text in it, Second will select To Hide textbox by name locator and type text in it, Third will select butter checkbox by xpath and select it, fourth will select cheese checkbox by css selector and select it.
No comments:
Post a Comment