Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I know that WebDriver can locate links through their text, using find_element_by_link_text or find_element_by_partial_link_text.

Is it possible to locate any element (such as li, div, span, ...) by text?

share|improve this question
up vote 17 down vote accepted

Yes. WebDriver supports using an XPath to locate an element by the text it contains. For example, the following XPath locates any div containing the string "Hello Justin":

//div[contains(.,'Hello Justin')]
share|improve this answer
Thanks, that's great. I'm new to xpath. Do you know if WebDriver supports xpath 2.0? – Randomblue Jan 25 '12 at 14:47
According to, WebDriver uses whatever XPath support is available in the browser. In other words, if the browser supports XPath 2.0, WebDriver should too. – user246 Jan 25 '12 at 15:12
Thank you user246! – Randomblue Jan 25 '12 at 15:14
The expression //div[contains() .... is an invalid expression. – djangofan Apr 6 '12 at 20:49
Thank you, djangofan. I will correct my answer. – user246 Apr 6 '12 at 21:24

As User246 mentioned, the xpath support depends on the browser. I have found a few problems with using XPath cross-browser. My solution for this problem was to find elements by tag name first, then iterate through the list of elements matching the tag and look for the attributes that I want to match on as well.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.