javaseleniumxpathwebdrivertestautomationfx

Get The Element "Text" from xml in selenium Java


I have the follwing nodes in XML :

<div class="publishing" xpath="1">
Par Aymen Test - aymen.test@test.fr
<br>
<time datetime="2022-10-11T16:01:20+02:00">Publié le 11/10/2022 à 16h01</time>
</div>

I want to get the text element following the class "publishing" Knowing that I can't use the content of text because it changes.

I tried with :

WebElement MyText = driver.findElement(By.xpath ("//div[@class='publishing']"));
System.out.println(MyText.getText());

But I get :

Par Aymen Test - aymen.test@test.fr
Publié le 11/10/2022 à 16h01

I need just :

Par Aymen Test - aymen.test@test.fr

Solution

  • You can get the total text and then remove from it the text content of child elements.
    This should work:

    WebElement parentEl = driver.findElement(By.xpath ("//div[@class='publishing']"));
    String totaltext = parentEl.getText();
    List<WebElement> children = parentEl.findElement(By.xpath (".//*"));
    for(WebElement child : children){
        totaltext = totaltext.replace(child.getText(), "");
    }
    System.out.println(totaltext);