How would I get selenium python to recognise this button in HTML?
I’ve tried this and other tags to get it
JavaScript
x
3
1
driver.find_element_by_class_name('cookie-monster').clickbutton
2
print('button was clicked')
3
This is the button snippet code
JavaScript
1
5
1
<button class="cookie-monster__cta cookie-monster__cta--primary js-cookie-monster-accept">
2
<span class="glyphicon glyphicon-ok"></span>
3
Accept All Cookies
4
</button>
5
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.
JavaScript
1
10
10
1
from selenium.webdriver.support.wait import WebDriverWait
2
from selenium.webdriver.support import expected_conditions as EC
3
from selenium.webdriver.common.by import By
4
5
wait = WebDriverWait(driver, 20)
6
wait.until(EC.element_to_be_clickable(
7
(By.CSS_SELECTOR, "js-cookie-monster-accept")))
8
button = driver.find_element_by_css_selector("js-cookie-monster-accept")
9
button.click()
10
If this locator is not unique, add classes one by one to both wait
and find_element_by_css_selector
, like this:
JavaScript
1
2
1
.js-cookie-monster-accept.cookie-monster__cta
2