- 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 “class name” in Selenium?
We can find an element using the attribute class name with Selenium webdriver using the locators - class name, css, or xpath. To identify the element with css, the expression should be tagname[class='value'] and the method to be used is By.cssSelector.
To identify the element with xpath, the expression should be //tagname[@class='value']. Then, we have to use the method By.xpath to locate it. To locate an element with a locator class name, we have to use the By.className method.
Let us look at the html code of an element with class attribute −
Syntax
WebElement e = driver. findElement(By.className("input")); WebElement m = driver. findElement(By.xpath("//input[@class = 'input']")); WebElement n = driver. findElement(By.cssSelector("input[class='input']"));
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 LocatorClsName{ 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.tutorialspoint.com/videotutorials/subscription.php"); // identify element with class WebElement n = driver.findElement(By.className("input")); n.sendKeys("JavaScript"); //identify element with cssSelector WebElement n = driver. findElement(By.cssSelector("input[class='input']")); String str = n.getAttribute("value"); System.out.println("Attribute value is : " + str); //identify element with xpath WebElement p = driver. findElement(By.xpath("//input[@class='input']")); p.clear(); driver.close(); } }
Output
Advertisements