Home > Back-end >  How to extract text using Selenium getText() method and Java
How to extract text using Selenium getText() method and Java

Time:03-11

My problem is to exactly identify a specific text on a website.

My actual solution is with Xpath and it works but I do not want to use Xpath and I only get the whole string and not just the specific pattern.

I tried with cssSelector and I did not figure it out. Same for id="top".

I want from this pattern:

Your user name is: username1 ... 
Just this part: username1

Environment:

openjdk 11 2018-09-25
OpenJDK Runtime Environment 18.9 (build 11 28)
OpenJDK 64-Bit Server VM 18.9 (build 11 28, mixed mode)

JUnit5
selenium-java-4.0.0-alpha-1
Eclipse Version: 2021-03 (4.19.0)

HTML:

<vaadin-horizontal-layout style="width: 100%; align-items: center;" id="top" slot="navi">
</iron-icon>
<iron-icon style="cursor: pointer; color: var(--lumo-primary-color); margin-right: 20px;" icon="vaadin:top-o" title="Sitename">
</iron-icon><iron-icon style="cursor: pointer; color: var(--lumo-primary-color); margin-right: 20px;" icon="vaadin:tabs" title="new window">
</iron-icon>
<span style="margin-left: auto; color: var(--lumo-primary-color); margin-right: 20px;">Your user name is: username1</span>

As I read it it is not an iron-icon.

This is what I have but it is not what I want:

Java Selenium Xpath:

System.out.println("text username");
Assert.assertEquals("Your user name is: username1", driver.findElement(By.xpath("/html/body/vaadin-app-layout/vaadin-horizontal-layout/span")).getText());
System.out.println("Get Text: ");
System.out.println(driver.findElement(By.xpath("/html/body/vaadin-app-layout/vaadin-horizontal-layout/span")).getText());

Does anyone has an idea how to address that specific username1 pattern in this vaadin environment?

CodePudding user response:

To extract the text username1 you have to induce WebDriverWait for the visibilityOfElementLocated() and you can use either of the following Locator Strategies:

  • Using xpath and split():

    String[] xpathParts = new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[contains(., 'Your user name is')]"))).getText().split(" ");
    System.out.println(xpathParts[4]);
    
  • Related