15

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?

19

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 Jan 25 '12 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 Jan 25 '12 at 15:12
  • 1
    The expression //div[contains() .... is an invalid expression. – djangofan Apr 6 '12 at 20:49
2

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, privacy policy and cookie policy

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