Selenium cannot find_element button by text if the said button also contains e.g. icon next to the text

Viewed 20

I am trying to select a button by text that looks like this:

<button>
  <svg focusable="false" aria-hidden="true" viewBox="0 0 24 24">
    <path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6v2z"></path>
  </svg> 

  The button
</button>

I am trying to utilize the find_element API:

browser.find_element(By.XPATH,'//button[text()="The button"]')

I believe it is because of the svg element in there, but I am not sure.

I would like to be able to make assertions like this without the need for unique selectors (id or similar).

1 Answers

Possibly parent element text content contains the text content of it child elements.
Also looks like the button element itself text content contains white spaces in addition to The button text here.
So, instead of browser.find_element(By.XPATH,'//button[text()="The button"]') please try this:

browser.find_element(By.XPATH,'//button[contains(.,"The button")]')

You can also try locating that element by removing the trailing and leading spaces with the use of normalize-space() as following:

browser.find_element(By.XPATH,'//button[normalize-space()="The button"]')
Related