Try the following:
driver.find_elements_by_xpath("//*[contains(text(), 'My Button')]")
Answer from Ricky Sahu on Stack OverflowTry 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
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 + "']")
How to get text with Selenium WebDriver in Python - Stack Overflow
Selenium -Python object identification issue
How to search for text in selenium
You can use XPath (code uses lxml.html)
>>> doc.xpath('//h1[text() = "AS Law"]')
[<Element h1 at 0x1075308f0>]In selenium the method has a different name:
https://selenium-python.readthedocs.io/locating-elements.html#locating-by-xpath
More on reddit.comSelenium: find element by text
link_text references the href of a link. You are looking for the inner text of a tag:
browser.find_elements_by_xpath("//*[contains(text(), 'TEXTO')]")