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?

2 Answers 2


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')]
  • Thanks, that's great. I'm new to xpath. Do you know if WebDriver supports xpath 2.0?
    – Randomblue
    Commented Jan 25, 2012 at 14:47
  • According to seleniumhq.org/docs/03_webdriver.html#commands-and-operation, WebDriver uses whatever XPath support is available in the browser. In other words, if the browser supports XPath 2.0, WebDriver should too.
    – user246
    Commented Jan 25, 2012 at 15:12
  • 1
    The expression //div[contains() .... is an invalid expression.
    – djangofan
    Commented Apr 6, 2012 at 20:49

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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