Search code examples
pythonselenium-webdriverxpathiframecss-selectors

How to locate the modal div element within an iframe using Selenium


I'm trying to get the <div> element within an iframe, but not able to find it.

Here is what I am trying to do:

options = webdriver.ChromeOptions() driver = webdriver.Chrome(options=options) driver.get("https://meuvaptvupt.com.br/pagina/agendamento")
try:
    time.sleep(5)
    modal = driver.find_element(by=By.ID, value="seleciona-cidade")
    print(modal) except NoSuchElementException:
    print("can't find it!!!") except:
    print("another error")
driver.quit()

The page doesn't show the element that I want. Some tips on how to do it?

What I want to see is a modal element, with the id seleciona-cidade, from the URL https://meuvaptvupt.com.br/pagina/agendamento


Solution

  • The element with ID as seleciona-cidade is the Modal Overlay

    seleciona-cidade


    Solution

    If your usecase is to click or send a character sequence within the query field, the desired element 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://meuvaptvupt.com.br/pagina/agendamento")
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a#accept-cookie"))).click()
        WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#iframe-agendamento")))
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "span.au-target +input[placeholder='Busque e selecione a cidade desejada']"))).click()
        
      • Using XPATH:

        driver.get("https://meuvaptvupt.com.br/pagina/agendamento")
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//a[@id='accept-cookie']"))).click()
        WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='iframe-agendamento']")))
        WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='au-target' ]//following::input[@placeholder='Busque e selecione a cidade desejada']"))).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:

    agendamento


    Reference

    You can find a couple of relevant discussions in: