- 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 get the attribute value of a web element in Selenium (using Java or Python)?
We can get the attribute value of a web element with Selenium webdriver using the method getAttribute and then pass the attribute for which we want to get the value as a parameter to that method.
In an html code, an element is defined with attributes and its values in a key-value pair. Let try to get the class – heading, for the below element on the page −
Syntax
WebElement t =driver.findElement(By.xpath("//li[text()='About Tutorialspoint']")); String s = t.getAttribute("class");
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 AttribtValue{ 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/about/about_careers.htm"); // identify element with xpath WebElement t =driver. findElement(By.xpath("//li[text()='About Tutorialspoint']")); //get value of class attribute String s = t.getAttribute("class"); System.out.println("Class attribute value is : " + s); driver.close(); } }
Output
Advertisements