Search code examples
pythonseleniumxpathiframecss-selectors

Python Selenium: Unable to find xpath to click on element within iframe


I'm using this code but the can't get it to work with the xpath:

browser = webdriver.Chrome(chrome_path)
browser.get("https://planetradio.co.uk/cool-fm")
time.sleep(5)
browser.find_element_by_xpath('//*[@id="notice"]/div[4]/button[2]').click()

Solution

  • The element ACCEPT ALL 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://planetradio.co.uk/cool-fm/')
        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='ACCEPT ALL']"))).click()
        
      • Using XPATH:

        driver.get('https://planetradio.co.uk/cool-fm/')
        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='ACCEPT ALL']"))).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
      
    • Browser Snapshot:

    planetradio


    References

    You can find a couple of relevant discussions in: