Home > Blockchain >  Unable to click on an element using CssSelector and Selenium Python
Unable to click on an element using CssSelector and Selenium Python

Time:03-11

I open this site in python https://zeitung.faz.net/ when open a message in popup this site

driver.find_element_by_css_selector("#notice > div.message-component.message-row.sticky-element > div.message-component.message-row.row-no-margin-phone.cta-yep > div").click()

but not work

CodePudding user response:

The element ZUSTIMMEN is within an <iframe> so you have to:

  • Induce WebDriverWait for the desired frame to be available and switch to it.

  • Induce WebDriverWait for the desired element to be clickable.

  • You can use either of the following Locator Strategies:

    • Using CSS_SELECTOR:

      driver.get('https://zeitung.faz.net/')
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe[title='SP Consent Message']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button[title='ZUSTIMMEN']"))).click()
      
    • Using XPATH:

      driver.get('https://zeitung.faz.net/')
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='SP Consent Message']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[@title='ZUSTIMMEN']"))).click()
      
  • Note : You have to add the following imports :

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

Reference

You can find a couple of relevant discussions in:

  • Related