<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.
<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.
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.