Skip to content
Advertisement

How to get Selenium to recognise a button and click it?

How would I get selenium python to recognise this button in HTML?

I’ve tried this and other tags to get it

 driver.find_element_by_class_name('cookie-monster').clickbutton
        print('button was clicked')

This is the button snippet code

<button class="cookie-monster__cta cookie-monster__cta--primary js-cookie-monster-accept">
<span class="glyphicon glyphicon-ok"></span>
Accept All Cookies
</button>

Advertisement

Answer

Your locator is wrong. The class is named cookie-monster__cta, not .cookie-monster. js-cookie-monster-accept seems to be unique class name. Use it for finding your element. Also, you should wait for elements before clicking them.

from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

wait = WebDriverWait(driver, 20)
wait.until(EC.element_to_be_clickable(
                (By.CSS_SELECTOR, "js-cookie-monster-accept")))
button = driver.find_element_by_css_selector("js-cookie-monster-accept")
button.click()

If this locator is not unique, add classes one by one to both wait and find_element_by_css_selector, like this:

.js-cookie-monster-accept.cookie-monster__cta
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement