How to retieve specific text from a tag without using contains() and xpath?


How to retieve specific text from a tag without using contains() and xpath?


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





Show how did you try, current and desired output, add tag for your programming language
– Andersson
Jul 2 at 10:21






Assuming that the typo <label1? is fixed, and that there are no other divs in the document, //div/text() will select Thor.
– jsheeran
Jul 2 at 10:29


<label1?


div


//div/text()


Thor





@jsheeran , not in Selenium
– Andersson
Jul 2 at 10:31





@Andersson Can you help me out dude?
– vny uppara
Jul 2 at 10:52





Update the question with a bit more of the outerHTML
– DebanjanB
Jul 2 at 11:13




3 Answers
3



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



xpath:


xpath


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



cssSelector:


cssSelector


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



Using JavaScriptExecutor


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.


//div[not(@label)]


div:not(label)



Could you please try the below mentioned path ?


/div/text()



Try to execute JavaScript via JavascriptExecutor


return document.querySelector('div').lastChild.textContent;



to get required text






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Rothschild family

Cinema of Italy