How can I get the current contents of an element in webdriver?


We can get the current contents of an element in Selenium webdriver. For the elements having tagname as <input> we have to use the getAttribute() method and pass the value parameter as an argument to that method to obtain the current contents.

For the elements without an input tag we have to use the getText() method to obtain the current contents. First of all we have to identify the element with the help of the locators.

Let us try to get the content Selenium inside the edit box and its above text content – You are browsing the best resource for Online Education.

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 ElementContent{
   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/index.htm");
      // identify elements
      WebElement t = driver.findElement(By.cssSelector("h4"));
      WebElement l = driver.findElement(By.id("gsc-i-id1"));
      // getAttribute() with value for content in edit box
      System.out.println("Content in edit box: " + l.getAttribute("value"));
      //getText() to get content
      System.out.println("Content in element: " + t.getText());
      driver.close();
   }
}

Output

Updated on: 18-Sep-2020

279 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements