Home > other >  How to find all buttons which contains a specific string using selenium python?
How to find all buttons which contains a specific string using selenium python?

Time:12-22

I want to find all buttons on the page which contain the word "card" or the word "bag".

For example it could be "add to card" or "add to bag" or "card" etc.

from selenium import webdriver 
from selenium.webdriver.support.color import Color
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome(executable_path = ChromeDriverManager().install())
driver.get('https://www.inshoes.gr/andrikes-zones-andrikes-zones-dermatines-diplis-opseos-33000481-kamel-mavro')
buttons=driver.find_element_by_xpath('//button[normalize-space()="Click me!"]')

for button in buttons:
    print (button)

CodePudding user response:

I use the following for this exact use case (for accepting cookies):

buttons = driver.find_elements_by_xpath("//button[contains(text(), 'Accept cookies')]") # Try Click Cookies

You can interchange the text as you like.

CodePudding user response:

To find all buttons on the page which contain the word card or the word bag you can clubup the conditions using within a lambda expression and you can use the following Locator Strategy:

elements = WebDriverWait(driver,20).until(lambda driver: driver.find_element(By.XPATH,"//button[contains(., 'card')]") or driver.find_element(By.XPATH,"//button[contains(., 'bag')]"))
  • Related