getAttribute() in Selenium
In this example, we have opened the Geeks For Geeks website (link), then we have found an element and obtained the class attribute of the specific element using getAttribute() function.
//Importing the Selenium libraries
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.By;
public class selenium3 {
public static void main(String[] args) {
//specify the location of the driver
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\Vinayak Rai\\Downloads\\chromedriver-win32\\chromedriver-win32\\chromedriver.exe");
//Initialising the driver
WebDriver driver = new ChromeDriver();
//Launch the website
driver.get("https://www.w3wiki.org/");
// Find an element
WebElement val=driver.findElement(By.xpath("/html/body/div[2]/div/div/div/div[1]/div[1]/div[1]"));
// Print the class attribute of element
System.out.println(val.getAttribute("class"));
// Close the web driver
driver.quit();
}
}
Output:
Difference between getText() and getAttribute() in Selenium WebDriver
A collection of libraries that lets the user perform numerous actions on the webpages autonomously is known as Selenium. There are certain ways to get information about an element in Selenium, i.e., getText() and getAttribute(). The getText function is contrary to getAttribute and should be used depending on their appropriate need. In this article, we will compare both of these functions.
Table of Content
- Difference between getText() and getAttribute() in Selenium WebDriver
- Examples of getText() and getAttribute()
- 1. getText() in Selenium
- 2. getAttribute() in Selenium
- Conclusion