How do I find an element that contains specific text in Selenium WebDriver (Python)? How do I find an element that contains specific text in Selenium WebDriver (Python)? python python

How do I find an element that contains specific text in Selenium WebDriver (Python)?


Try the following:

driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")


You could try an XPath expression like:

'//div[contains(text(), "{0}") and @class="inner"]'.format(text)


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


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']]")

XPath expression for variable text

In case the text is a variable, you can use:

foo= "foo_bar"my_element = driver.find_element_by_xpath("//div[.='" + foo + "']")


matomo