Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding xpath from text with br

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.

like image 709
Etienne Avatar asked May 10 '17 15:05

Etienne


People also ask

How do I use XPath in text?

Using XPath- text() method, we can write the Java code along with the dynamic XPath location as: findElement(By. xpath("//*[text()='Google offered in')]"));

What is the difference between DOT and text in XPath?

enter image description here The XPath text() function locates elements within a text node while dot (.) locate elements inside or outside a text node.

What is TD and TR in XPath?

The < tr > tag in the table indicates the rows in the table and that tag is used to get information about the number of rows in it. Number of columns of the web table in Selenium are calculated using XPath (//*[@id='customers']/tbody/tr[2]/td).


1 Answers

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']
like image 87
Andersson Avatar answered Oct 10 '22 04:10

Andersson