Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selenium xpath selector based on the element text

What would a Selenium xpath selector be for the following HTML:

<ul>
   <li>First</li>
   <li>Second</li>
   <li>Third</li>
</ul>

I need to make Selenium IDE locate the second item on the list based on the element text. I thought //li='Second' would do the trick, but apparently it does not.

like image 274
mfeingold Avatar asked Jun 26 '13 20:06

mfeingold


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 find an element that contains specific text in Selenium WebDriver?

We can find an element that contains specific text with Selenium webdriver in Python using the xpath. This locator has functions that help to verify a specific text contained within an element. The function text() in xpath is used to locate a webelement depending on the text visible on the page.

What is the correct way to select an element that contains target text?

What is the correct way to select an element that contains “target text”? WebElement element = driver. findElement(By. xpath("//*[contains(text(), 'target text')]"));


4 Answers

I think this is what you are looking for

ul/li[contains(text(), "Second")]

and better still

ul/li[text() = 'Second']
like image 159
Amey Avatar answered Oct 11 '22 23:10

Amey


If you want to get by text

[.= 'Second']

or

[text() = 'Second']
like image 29
Adnan Ghaffar Avatar answered Oct 11 '22 22:10

Adnan Ghaffar


By.xpath( "//li[contains(text(), 'Second')]" )
like image 5
Hai Nguyen Avatar answered Oct 11 '22 23:10

Hai Nguyen


You can use like this:

//li[. = "Second"]

OR

//li[contains(., "Second")]

Here, contains mean that you can match the partial text, so below one is also correct:

//li[contains(., "Seco")]
like image 3
Pratik Patel Avatar answered Oct 12 '22 00:10

Pratik Patel