Articles → SELENIUM → Locate Web Elements By Name And Id In Selenium
Locate Web Elements By Name And Id In Selenium
What Does Locating A Web Element Mean?
Syntax
// Locating by Id
driver.findElement(By.id("control_id"));
// Locating by name
driver.findElement(By.name("control name"));
Example
Click to Enlarge
- Write ‘Test’ in email id textbox and we will access the textbox using ‘id’ attribute.
- Clears the text from email id textbox and we will access the textbox using ‘name’ attribute.
Click to Enlarge
package com.FirstSeleniumProject;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
public class MyClass {
public static void main(String[] args) {
WebDriver driver;
String service = "IEDriverServer path";
System.setProperty("webdriver.ie.driver", service);
driver = new InternetExplorerDriver();
driver.get("http://gyansangrah.com/ContactUs.aspx");
// Locating by Id
driver.findElement(By.id("ctl00_cphGyanSangrah_txtEmailID")).sendKeys("Test");
// Locating by name
driver.findElement(By.name("ctl00$cphGyanSangrah$txtEmailID")).clear();
}
}
Output
Click to Enlarge