I am trying to write python code that clicks the "accept the cookies" button, but it doesn’t work. I could not understand the problem. Can you help me? Here is my code:
Note: I am using MS Visual code, and
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://stackoverflow.com/")
driver.maximize_window()
driver.find_element(By.CLASS_NAME, "flex--item6 s-btn s-btn__primary js-accept-cookies js-consent-banner-hide").click()
My goal is automatic clicking the accept the cookies button, but the code that I run has problem, and I did not understand the problem.
The HTML of the button is:
<button
class="flex--item6 s-btn s-btn__primary js-accept-cookies js-consent-banner-hide">
Accept all cookies
</button>
How can add HTML of the button? Was my way wrong?
I also added implicity wait like this: driver.implicitly_wait(15) but it doesn’t click still.
>Solution :
I would recommend the following.
-
Try using some different element selector such
By.XPATH(copy as full xpath) ,By.ID,By.CSS_SELECTOR -
Try using sleep methods as you don’t want to happen the whole process so quickly.
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
import time
PATH = "C:\Program Files (x86)\chromedriver.exe"
driver = webdriver.Chrome(PATH)
driver.get("https://stackoverflow.com/")
time.sleep(1)
driver.maximize_window()
time.sleep(1)
driver.find_element(By.XPATH, '/html/body/div[4]/div[1]/button[1]').click() #full XPATH
time.sleep(5)
I hope this would help.