Difference b/w getText() and getAttribute() in Selenium WebDriver?

SeleniumAutomation TestingTesting Tools

The differences between getText() and getAttribute() methods are described below. The getText() method returns the innerText of an element. The text which is visible on the page along with sub elements. It ignores all leading and trailing spaces.

The getAttribute() method fetches the text contained by an attribute in an html document. If a value is not set for an attribute, null value is returned. The attribute is passed as a parameter to the method.

So the getText() method gives the text present between the start and end html tags (which is not hidden by CSS) and the getAttribute() method identifies the key value pairs within the html tags.

In the above html code, style is an attribute whose value can be obtained from getAttribute() method. If we apply the getText() method on that element, we shall get the text.

Example

Code Implementation with getText().

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 GetTextMethd{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://www.tutorialspoint.com/videotutorials/subscription.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElements(By.cssSelector("h2"));
      // extract text with getText()
      System.out.println("getText() method:" + l.getText());
      driver.quit();
   }
}

Output

Example

Code Implementation with getAttribute().

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 GetAttributeMethd{
   public static void main(String[] args) {
      System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String url ="https://www.tutorialspoint.com/videotutorials/subscription.php";
      driver.get(url);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify element
      WebElement l = driver.findElements(By.cssSelector("h2"));
      // get style attribute with getAttribute()
      System.out.println("getAttribute() method:" + l.getAttribute("style"));
      driver.quit();
   }
}

Output

raja
Published on 28-Aug-2020 13:01:52
Advertisements