
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check Element for Specific Class Attribute Using Selenium
We can check if an element contains a specific class attribute value. The getAttribute() method is used to get the value of the class attribute. We need to pass class as a parameter to the getAttribute() method.
First of all we need to identify the element with help of any of the locators like id, class, name, xpath or css. Then obtain the class value of the attribute. Finally, we need to check if the class attribute contains a specific value.
Let us take an element with the below html code having class attribute. The tp-logo is the value of the class attribute.
Example
import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class SpecificClassVal{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); driver.get("https://www.tutorialspoint.com/about/about_careers.htm"); // identify element WebElement t=driver.findElement(By.xpath("//img[@class='tp-logo']")); // get class attribute with getAttribute() String clsVal = t.getAttribute("class"); //iterate through class value for (String i : clsVal.split(" ")) { //check the class for specific value if (i.equals("tp-logo")) { System.out.println("class attribute contains: " + clsVal); } else { System.out.println("class attribute does not contain: " + clsVal);} } driver.close(); } }
Output
Advertisements