Java - Extract Text Which Contains Tag with Selenium Webdriver

Java - Extract Text Which Contains Tag with Selenium Webdriver

I'm trying to extract text from following HTML code :

<div>
   "blabla"
   <br>
   "blublu"
   <br>
   "blibli"
</div>

I'm using getAttribute method because the text can be hidden (so getText() can possibly return null) :

String text = driver.findElement(By.tagName("div")).getAttribute("textContent");
System.out.println(text);

the expected result is

blabla\nblublu\nblibli

however I get

blablablublublibli
1

2 Answers

You can use getText() method on the WebElement

driver.findElement(By.xpath("//div")).getText()

Output would be something like:-

"blabla"
"blublu"
"blibli"
1

Problem resolved by using

String text = driver.findElement(By.tagName("div")).getAttribute("innerText");

and not

String text = driver.findElement(By.tagName("div")).getAttribute("textContent");
1
Marcus Vance
Author

Marcus Vance

Marcus Vance is a cybersecurity auditor and technology writer dedicated to educating the public about online safety, data privacy regulations, enterprise security, and emerging cyber threats.