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




Picture showing the contact page of the website gyansangrah.com
Click to Enlarge



  1. Write ‘Test’ in email id textbox and we will access the textbox using ‘id’ attribute.
  2. Clears the text from email id textbox and we will access the textbox using ‘name’ attribute.


Picture showing the rendered HTML of the contact us form
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




Picture showing how to Locate web elements by name and id in selenium
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Wednesday, March 29, 2017

Query/Feedback


Your Email Id  
 
Subject 
 
Query/FeedbackCharacters remaining 250