TestProject Forum
Powered by leading experts in the test automation community

Find an element that contains specific text with Selenium in Python

I want to be able to search for elements based on text “button”

driver.find_elements_by_xpath('//div[contains(text(), "button")]')

I tried xpath/css but nothing seems to work

Try this:

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

Use the asterisk character * to find any/all elements that answer such criteria

I want to update the xpath to include keyword contains ,I used the below xpath but the recorder couldn’t find the element. however when i remove the contains , it works.

//[contains(text(), ‘Allow all the time’)]. = doesn’t work. .NOTE: I actually just want the word ‘Allow’ and have used asterisk after slashes .
//
[@text =‘Allow all the time’] = this works

Hello @it.dishantrawat
The contains function in the xpath finds an element which has a child node which contains the text.
For example //*[contains(text(), ‘Hello World’)] will search for all child elements of all parent elements in the DOM while [@text =‘Allow all the time’] searches all elements with that text of the current node.