Home > front end >  Clicking Accept cookies button using Selenium
Clicking Accept cookies button using Selenium

Time:08-05

I am trying to automate some download of data and have an issue with accepting the cookies message.

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

from selenium.webdriver.common.by import By
from random import randint
import time

current_link = "https://platform.smapone.com/Portal/Account/Login?ReturnUrl=/Portal/"
driver = webdriver.Chrome(PATH)
driver.maximize_window()
driver.implicitly_wait(10)
driver.get(current_link)
#driver.switch_to.frame("cookieConsentIframe")
#driver.switch_to.frame(driver.find_element_by_name('cookieConsentIframe'))

try:
    WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='cookieConsentIframe']")))
    print(1)
    driver.find_element(By.XPATH,'//button[@id="cookies-accept-all"]').click()
    #driver.find_element(By.XPATH,'//button[text()="Accept"]').click()
except:
    pass
 
time.sleep(randint(5,8))   
driver.quit()

The code runs through (prints also the 1) but never clicks the button. Any suggestions? Tried so many things already.

CodePudding user response:

You need to also wait out the button:

WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH,'//button[@id="cookies-accept-all"]'))).click()

EDIT Here is a full example (selenium/chromedriver setup is for python, but you need to observe only the imports, and part after defining the browser):

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support import expected_conditions as EC

import time as t

chrome_options = Options()
chrome_options.add_argument("--no-sandbox")

webdriver_service = Service("chromedriver/chromedriver") ## path to where you saved chromedriver binary
browser = webdriver.Chrome(service=webdriver_service, options=chrome_options)



url = 'https://platform.smapone.com/Portal/Account/Login?ReturnUrl=/Portal/'
browser.get(url)

WebDriverWait(browser, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='cookieConsentIframe']")))
    
## sortout cookie button
try:
    WebDriverWait(browser, 10).until(EC.element_to_be_clickable((By.XPATH,'//button[@id="cookies-accept-all"]'))).click()
    print("accepted cookies")
except Exception as e:
    print('no cookie button')

CodePudding user response:

The element Accept is within an smapone

  • Related