Take the 2-minute tour ×
Software Quality Assurance & Testing Stack Exchange is a question and answer site for software quality control experts, automation engineers, and software testers. It's 100% free, no registration required.

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

2 Answers 2

up vote 6 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 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
    
Thank you user246! –  Randomblue Jan 25 '12 at 15:14
1  
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

 
discard

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.