Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clicking the button with Selenium Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

  1. Try using some different element selector such By.XPATH(copy as full xpath) , By.ID, By.CSS_SELECTOR

  2. 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading