pythonseleniumselenium-webdriverseleniumwire

python selenium accept cookie iframe


I'm new in python and selenium and I need help. I can not accept cookie in to the iframe

Anybody can help me please?

Thanks

from selenium.webdriver.firefox.options import Options
from seleniumwire import webdriver

options = Options()
options.binary_location = r'C:\\Program Files\\Mozilla Firefox\\firefox.exe'

driver = webdriver.Firefox(executable_path=r'C:\\geckodriver.exe', firefox_options=options)


driver.get('https://autoscout24.de/')
time.sleep(5)
# go to iframe accept cookies
driver.switch_to.frame("gdpr-consent-notice")
driver.find_element_by_css_selector("button[class='mat-focus-indicator solo-button mat-button mat-button-base mat-raised-button cdk-focused cdk-mouse-focused'] div[class='action-wrapper']").cick()



# back to previous frame
driver.switch_to.parent_frame()
time.sleep(5)


driver, quit()

Solution

  • I see ID is unique then you do not need CSS Selector at all.

    You should induce Explicit waits to switch to iframe.

    They allow your code to halt program execution, or freeze the thread, until the condition you pass it resolves. The condition is called with a certain frequency until the timeout of the wait is elapsed. This means that for as long as the condition returns a falsy value, it will keep trying and waiting.

    Code :

    driver = webdriver.Firefox(executable_path=r'C:\\geckodriver.exe', firefox_options=options)
    driver.maximize_window()
    wait = WebDriverWait(driver, 20)
    driver.get('https://autoscout24.de/')
    wait.until(EC.frame_to_be_available_and_switch_to_it((By.ID, "gdpr-consent-notice")))
    button = driver.find_element_by_id('save')
    driver.execute_script("arguments[0].click();", button)
    
    
    # back to previous frame
    driver.switch_to.parent_frame()
    time.sleep(5)
    

    Imports :

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