By id() method to locate the web element

Totally selenium webdriver have eight locating mechnism to find the element which will be passed to the findElement and findElements method.
  1. name
  2. id
  3. tagName
  4. class
  5. linkText
  6. partialLinkText
  7. XPath
  8. cssSelector
All the web page have attributes and its values.  We can search or locate the element by using one of these By method's.

In the below code example, user can locate the search button and its value from www.bing.com using By id method.
To driver the webbrowser, user need to locate the element which is present on the web page.

User can find the web element using firebug tool in firefox.  For chrome browser, user can use inspect element option by right clicking the mouse.
Code:
import java.util.concurrent.TimeUnit;  
import org.openqa.selenium.*;  
import org.openqa.selenium.firefox.FirefoxDriver;  

public class byName {
public static void main(String[] args){
 
//invoking firefox browser 
WebDriver driver = new FirefoxDriver();

//Launching bing website
driver.get("http://www.bing.com");

//Assigning the name attribute value to the variable using By.name
WebElement Bsearch = driver.findElement(By.name("go"));

//Locating the element using By.id
driver.findElement(By.id("sb_form_q")).sendKeys("www.qafreaks.com");

//Submit the search button
Bsearch.submit();

System.out.println("Successfully Searched using By ID");
}
}

Output:
Successfully Searched using By ID
Socialize It and Share the post with your friends
SOCIALIZE IT →
FOLLOW US →
SHARE IT →