FindElement() Method

Why do we need to locate the WebElements? Fine. Because, WebDriver will drive the browser with the help of WebElements such as HTML tags or XML tags.  What is WebElements? WebElements is nothing but the source code of the web page is decorated with lots of tags to build the webpage.

Example tags in the webpage source code are <title>, <div>, <a> and <span> etc., All the tags have attributes and their values for its specification.



In order to drive the browser, selenium scripts need to find the element and get the values of the attributes and perform the actions for automation.

Before we need to find the element value how can we locate it?  We can locate the elements using FireBug extension in firefox or Inspect Element in Chrome Browser.

Drag your mouse over the element and right click of your mouse, mouse options will be listed and click inspect element.

findElement() method and By.name() method are the WebElement
interface. The findElement() and By() methods instructs WebDriver to locate a WebElement on a web page, and once found, the findElement() method returns the WebElement instance of that element. Hence, the input parameter for the findElement() method is the By instance. By instance is a WebElement - locating mechanism.


If WebDriver doesn't find the element and not satisfied the condition, it throws a runtime exception named NoSuchElementException, which is invoking class or method should handle.

Now open your Eclipse IDE or any editor which supports selenium scripts.
Copy and Paste the below scripts and Run it by Shortcut in eclipse to run (Ctrl + F11)

Code Input:
import org.openqa.selenium.By;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class FB_getUserID {
 
public static void main(String[] args) {

 //Invoke Firefox Browser
 WebDriver driver = new FirefoxDriver();
 
 //Open Facebook login page
 driver.get("http://www.facebook.com");
 
 //Find Element of the userid and password 
        //and assigning the value to the variable
 WebElement userId = driver.findElement(By.id("email"));
 WebElement userPwd = driver.findElement(By.id("pass"));
    
System.out.println("FaceBook Email id element is " +userId);
System.out.println("FaceBook Email id element is " +userPwd);

}
}
Output Result:
FaceBook Email id element is [[FirefoxDriver: firefox 
on WINDOWS (xxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx)] -> id: email]
FaceBook Email id element is [[FirefoxDriver: firefox 
on WINDOWS (xxxxxxx-xxxx-xxxx-xxx-xxxxxxxxxxxx)] -> id: pass]
Socialize It and Share the post with your friends
SOCIALIZE IT →
FOLLOW US →
SHARE IT →