Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve an xpath text contains using text()

Tags:

xpath

I've been hacking away at this one for hours and I just can't figure it out. Using XPath to find text values is tricky and this problem has too many moving parts.

I have a webpage with a large table and a section in this table contains a list of users (assignees) that are assigned to a particular unit. There is nearly always multiple users assigned to a unit and I need to make sure a particular user is assigned to any of the units on the table. I've used XPath for nearly all of my selectors and I'm half way there on this one. I just can't seem to figure out how to use contains with text() in this context.

Here's what I have so far:

//td[@id='unit']/span [text()='asdfasdfasdfasdfasdf (Primary); asdfasdfasdfasdfasdf, asdfasdfasdfasdf; 456, 3456'; testuser] 

The XPath Query above captures all text in the particular section I am looking at, which is great. However, I only need to know if testuser is in that section.

like image 515
Brian Avatar asked Jan 28 '13 20:01

Brian


People also ask

Can we use text () in XPath?

5) XPath Text() FunctionThe XPath text() function is a built-in function of selenium webdriver which is used to locate elements based on text of a web element. It helps to find the exact text elements and it locates the elements within the set of text nodes. The elements to be located should be in string form.

How do I get the text of an element using XPath?

So, inorder to find the Text all you need to do is: driver. findElement(By. xpath("//*[contains(text(),'the text you are searching for')]"));

Can we use contains in XPath?

contains() in Selenium is a function within Xpath expression which is used to search for the web elements that contain a particular text. We can extract all the elements that match the given text value using the XPath contains() function throughout the webpage.


1 Answers

text() gets you a set of text nodes. I tend to use it more in a context of //span//text() or something.

If you are trying to check if the text inside an element contains something you should use contains on the element rather than the result of text() like this:

span[contains(., 'testuser')] 

XPath is pretty good with context. If you know exactly what text a node should have you can do:

span[.='full text in this span'] 

But if you want to do something like regular expressions (using exslt for example) you'll need to use the string() function:

span[regexp:test(string(.), 'testuser')] 
like image 180
underrun Avatar answered Oct 06 '22 20:10

underrun