5
votes

I have this html code

<div>
  <span>test</span>
  foo
  <br />
  bar
</div>

And I'm trying to find it with the text directly inside the div (so foo bar).

Normally, I would go //div[normalize-space(text()) = 'foobar'], but because of the
it is not working. I tried to add spaces or special chars, or trim them, but nothing seem to work.

From tests I saw that

//div/text() = foo bar
//div/text()[1] = foo
//div/text()[2] = bar
//div[text()[1] = foo] = the div
//div[text()[2] = bar] = nothing

It seem that text() return only a index[2] when returning a value and not for searching a value.

I tested this code with java / selenium and firepath (a plugin of firebug to test xpath).

Anybody have an idea on how to get the div from the text, and if possible, without using contains because they are not accurate.

Thank you.

2

2 Answers

3
votes

You can try to use below XPath expression to match required div by its text:

//div[normalize-space()="test foo bar"]

Note that function to remove white-spaces called actually normalize-space(), but not sanitize-space()

Update

If you want to use only "foo" and "bar" text nodes, then try

//div[concat(normalize-space(text()[2]), normalize-space(text()[3]))="foobar"]')

or if to use them separately

//div[normalize-space(text()[2])='foo' and normalize-space(text()[3])='bar']
1
votes

You can also try following:

  //span[text()='test']/ancestor::div

UPDATE 1:

  //div[contains(.,'foo')]

UPDATE 2:

   //span/ancestor::div[contains(.,'foo')]