How Do I Find an Element That Contains Specific Text in Selenium Webdriver (Python)?
I'm Trying to Test a Complicated Javascript Interface with Selenium (Using the Python Interface, and Across Multiple Browsers). I Have a Number of Buttons of...
I'm trying to test a complicated JavaScript interface with Selenium (using the Python interface, and across multiple browsers). I have a number of buttons of the form:
<div>My Button</div>
I'd like to be able to search for buttons based on "My Button" (or non-case-sensitive, partial matches such as "my button" or "button").
I'm finding this amazingly difficult, to the extent to which I feel like I'm missing something obvious. The best thing I have so far is:
driver.find_elements_by_xpath('//div[contains(text(), "' + text + '")]')
This is case-sensitive, however. The other thing I've tried is iterating through all the divs on the page, and checking the element.text property. However, every time you get a situation of the form:
<div class="outer"><div class="inner">My Button</div></div>
div.outer also has "My Button" as the text. To fix that, I've tried looking to see if div.outer is the parent of div.inner, but I couldn't figure out how to do that (element.get_element_by_xpath('..') returns an element's parent, but it tests not equal to div.outer).
Also, iterating through all the elements on the page seems to be really slow, at least using the Chrome webdriver.
Ideas?
I asked (and answered) a more specific version here: How to get text of an element in Selenium WebDriver, without including child element text?
12 Answers
Try the following:
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
In the HTML which you have provided:
<div>My Button</div>
The text My Button is the innerHTML and have no whitespaces around it so you can easily use text() as follows:
my_element = driver.find_element_by_xpath("//div[text()='My Button']")
Note:
text()selects all text node children of the context node
Must Read
Text with leading/trailing spaces
In case the relevant text containing whitespaces either in the beginning:
<div> My Button</div>
or at the end:
<div>My Button </div>
or at both the ends:
<div> My Button </div>
In these cases you have two options:
You can use
contains()function which determines whether the first argument string contains the second argument string and returns boolean true or false as follows:my_element = driver.find_element_by_xpath("//div[contains(., 'My Button')]")You can use
normalize-space()function which strips leading and trailing white-space from a string, replaces sequences of whitespace characters by a single space, and returns the resulting string as follows:driver.find_element_by_xpath("//div[normalize-space()='My Button']]")