mariohanna12
mariohanna12

Reputation: 15

Python Selenium, cant find and click element by id even if it exists

My script should open a page and click the consent button on the occuring popup. My code:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time

s=Service(ChromeDriverManager().install())
driver = webdriver.Chrome(service=s)
driver.maximize_window()

def webde_reg():
    driver.get('https://web.de/consent-management')
    time.sleep(5)
    consent_button = driver.find_element(By.ID, "save-all-conditionally")
    consent_button.click()
    time.sleep(2)


webde_reg()

Sadly, no matter if i try it via xpath or id the element cant be found. Is it because it is a popup and wont be recognized? how to resolve?

Upvotes: 0

Views: 581

Answers (1)

Dev
Dev

Reputation: 2813

There are 2 nested iframes before the popup, before reaching for the popup confirmation you will have to switch the iframes, There is only one iframe inside the outer most iframe so just identifying it using tag name. First iframe can be identified using classname attribute. Since there is delay on the page to see the popup I have used expected condition with wait.

def webde_reg():
    driver.get('https://web.de/consent-management')
    #wait and switch to the first iframe
    wait.until(expected_conditions.frame_to_be_available_and_switch_to_it((By.CLASS_NAME, 'permission-core-iframe')))
    # switch to the 2nd iframe
    driver.switch_to.frame(driver.find_element_by_tag_name('iframe'))
    wait.until(expected_conditions.presence_of_element_located((By.XPATH, ".//button[@id='save-all-conditionally']")))
   
    consent_button = driver.find_element(By.ID, "save-all-conditionally")
    consent_button.click()

    # move to default content 
    driver.switch_to.default_content()

driver.switch_to.default_content() this line will allow you to move out of all the iframes, and then you can interact with the default content on the page if at all there is no frame existing after the accepting the confirmation popup.

You will need below imports-

from selenium.webdriver.support import expected_conditions  # as EC
from selenium.webdriver.support.ui import WebDriverWait

Output: enter image description here

Upvotes: 1

Related Questions