- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find an element using the attribute “id” in Selenium?
We can find an element using the attribute id with Selenium webdriver using the locators - id, css, or xpath. To identify the element with css, the expression should be tagname[id='value'] and the method to be used is By.cssSelector.
To identify the element with xpath, the expression should be //tagname[@id='value']. Then, we have to use the method By.xpath to locate it. To locate an element with locator id, we have to use the By.id method.
Let us look at the html code of an element with id attribute −
Syntax
WebElement e = driver. findElement(By.id("session_key")); WebElement m = driver. findElement(By.xpath("//input[@id=' session_key']")); WebElement n = driver. findElement(By.cssSelector("input[id=' session_key']"));
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.firefox.FirefoxDriver; import java.util.concurrent.TimeUnit; public class LocatorId{ public static void main(String[] args) { System.setProperty("webdriver.gecko.driver", "C:\Users\ghs6kor\Desktop\Java\geckodriver.exe"); WebDriver driver = new FirefoxDriver(); //implicit wait driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //URL launch driver.get("https://www.linkedin.com/"); // identify element with Id WebElement l = driver.findElement(By.id("session_key")); l.sendKeys("Java"); //identify element with css WebElement m = driver. findElement(By.cssSelector("input[id='session_key']")); String s = m.getAttribute("value"); System.out.println("Attribute value: " + s); //identify element with xpath WebElement n = driver. findElement(By.xpath("//input[@id='session_key']")); n.clear(); driver.quit(); } }
Output
Advertisements