Search code examples
javaselenium-webdrivergettextwebdriverwaitgetattribute

How to extract the text from the element using Selenium through Java


How can I get text of this element:

<div class="status-value" id="divdoctyp" xpath="1">AADHAAR CARD</div>

I tried this

WebElement doctype= driver.findElement(By.xpath("//div[@id='divdoctyp']"));
String type=doctype.getAttribute("type"); 
String label=doctype.getText();
Thread.sleep(5000);
System.out.print("doctype is "+type +"\n"+label);

Solution

  • To extract text AADHAAR CARD from the element you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

    • Using cssSelector and getAttribute():

      System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.status-value#divdoctyp"))).getAttribute("innerHTML"));
      
    • Using xpath and getText():

      System.out.println(new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='status-value' and @id='divdoctyp']"))).getText());