Home > Back-end >  Unable to get text values present within strong tag using Selenium Java
Unable to get text values present within strong tag using Selenium Java

Time:01-16

While trying to print values present with in strong tag using xpath I'm getting following exception:

org.openqa.selenium.NoSuchElementException: Unable to locate element: strong

This is my code :

WebElement eleText = driver.findElement(By.xpath("//strong"));
String testerName = eleText.getText();
System.out.println(testerName);

This is my webpage which I'm trying to get values within strong tag :

 <a id="id_1099808326" > 
    <strong>heizil</strong> : 
    <label id="check_label">  " First Device Test"
    </label>
    
    <a id="id_1099808296" > 
    <strong>riya</strong>: 
    <label id=check_label"> " Second Device Test"
    </label>

Expected output: heizil,riya

If this is not the proper way can any one suggest any other way of getting the values present in <strong> tag

CodePudding user response:

As per the given HTML text heizil is within <strong> tag which is the immediate descendant of the <a> tag.

<a id="id_109996" > 
    <strong>heizil</strong>
    : 
    <label id="sample_label">
        ...
        ...
    </label>
</a>

Solution

To print the text heizil you can use either of the following locator strategies:

  • Using cssSelector and getAttribute("innerHTML"):

    System.out.println(driver.findElement(By.cssSelector("a.activity > strong")).getAttribute("innerHTML"));
    
  • Using xpath and getText():

    System.out.println(driver.findElement(By.xpath("//a[@class='activity']/strong")).getText());
    

Ideally, to extract the text value, you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following locator strategies:

  • Using cssSelector and getText():

    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.activity > strong"))).getText());
    
  • Using xpath and getAttribute("innerHTML"):

    System.out.println(new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='a-link-normal' and @id='vvp-product-details-modal--product-title']"))).getAttribute("innerHTML"));
    
  • Related