How to get the text from <span> tag and use this text on other page using Selenium and Java

1k Views Asked by At

I want to get text included in a span tag.

Here's HTML

<div class="position">
<h1>
<span class="select-text">Some Text</span>
</h1>
</div>

And I've tried this

wd.findElement(By.xpath("//div[@class="position"]//h1//span")).getText();

But I get this error all the time and IDK what I'm doing wrong

org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//div[@class="position"]//h1//span"}

Additional problem: after getting a text from this page I need to make sure if this text is not visible on another page. If you have any idea how can I realize it I'll be grateful.

3

There are 3 best solutions below

0
On

I believe you will find that your xpath selector for div with class 'position' should be

div[contains(@class, 'position')]
0
On

To print the text Some Text from the <span> you can use either of the following Locator Strategies:

  • Using cssSelector and getAttribute("innerHTML"):

    System.out.println(wd.findElement(By.cssSelector("div.position>h1>span.select-text")).getAttribute("innerHTML"));
    
  • Using xpath and getText():

    System.out.println(wd.findElement(By.xpath("//div[@class='position']/h1/span[@class='select-text']")).getText());
    

Ideally, to extract the text Some Text as the element is a dynamic element, 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(wd, 20).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("div.position>h1>span.select-text"))).getText());
    
  • Using xpath and getAttribute("innerHTML"):

    System.out.println(new WebDriverWait(wd, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@class='position']/h1/span[@class='select-text']"))).getAttribute("innerHTML"));
    
0
On

Try this xpath:

wd.findElement(By.xpath("//div[contains(@class='position')]/h1/span[contains(text(), 'Some Text') ]")).getText () ;

If you need to check, if this text exists in another page or not, you need to write the generic xpath, which will capture the results. Compare your current string with another text using if loop.