Skip to main content
3 of 5
Active reading [<https://en.wiktionary.org/wiki/in_case#Conjunction> <https://en.wikipedia.org/wiki/XPath>].
Peter Mortensen
  • 31.4k
  • 22
  • 110
  • 134

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 + "']") 
undetected Selenium
  • 194.5k
  • 44
  • 304
  • 387