Adam Pengal Adam Pengal - 5 months ago 24x
Java Question

Selenium: Extract Text of a div with cssSelector in Java

I am writing a JUnit test for a webpage, using Selenium, and I am trying to verify that the expected text exists within a page. The code of the webpage I am testing looks like this:

<div id="recipient_div_3" class="label_spacer">
<label class="nodisplay" for="Recipient_nickname"> recipient field: reqd info </label>
<span id="Recipient_nickname_div_2" class="required-field"> *</span>

I want to compare what is expected with what is on the page, so I want to use
Assert.assertTrue(). I know that to get everything from the div, I can do

String element = driver.findElement(By.cssSelector("div[id='recipient_div_3']")).getText().replaceAll("\n", " ");

but this will return "reqd info * Recipient:"

Is there any way to just get the text from the div ("Recipient") using cssSelector, without the other tags?


You can't do this with a CSS selector, because CSS selectors don't have a fine-grained enough approach to express "the text node contained in the DIV but not its other contents". You can do that with an XPath locator, though:


That XPath expression will identify just the single text node that is a direct child of the DIV, rather than all the text contained within it and its child nodes.