0
<div>
    <label1>Hulk</label1>
    <label2>Ironman</label2>
Thor
</div>

How do I get only Thor text without using contains in xpath ?

If I try getting text of div it would give me all the 3 (Hulk, Ironman, Thor) but I want only Thor.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
vny uppara
  • 119
  • 6

2 Answers2

3

To extract the text Thor without using contains in xpath you can use either of the following solutions:

  • xpath:

    String myText = driver.findElement(By.xpath("//div[not(@label)]")).getText();
    
  • cssSelector:

    String myText = driver.findElement(By.cssSelector("div:not(label)")).getText();
    
  • Using JavaScriptExecutor

    WebElement myElement = driver.findElement(By.xpath("//div[@attribute='value']")); //replace the pseudo attribute with actual attribute
    String myText = ((JavascriptExecutor)driver).executeScript('return arguments[0].lastChild.textContent;', myElement).toString();
    

Note: Ensure that xpath as //div[not(@label)] and cssSelector as div:not(label) resembles to a unique element on the HTML DOM.

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

Could you please try the below mentioned path ?

/div/text()
Ananda R
  • 18
  • 5