Search code examples
seleniumiframewebdriverwebdriverwaitexpected-condition

Selenium - How to send keys within an iFrame?


I'm coding a selenium automated bot, and I want to send keys to a input that I got from iFrame, check the code line:

username = bot.find_element_by_xpath("//iframe[@title='Registration form' and @class='top']")

Can you guys help me? I can click on the input, but, on send the keys, it doesn't work and deselect the input field.


Solution

  • You don't send character sequence to the <iframe> element rather you would send character sequence to the <input> element within the <iframe>. As the the desired element is within a <iframe> so you have to:

    • Induce WebDriverWait for the desired frameToBeAvailableAndSwitchToIt.

    • Induce WebDriverWait for the desired elementToBeClickable.

    • You can use either of the following Locator Strategies:

    • Using XPATH:

      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@title='Registration form' and @class='top']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@attribure_name='attribute_value']"))).send_keys("Igor Duca")
      
    • Using CSS_SELECTOR:

      driver.get('https://www.t-online.de/themen/e-mail')
      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe.top[title='Registration form']")))
      WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[attribure_name='attribute_value']"))).send_keys("Igor Duca")
      
    • 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
      

    You can find a relevant detailed discussion in How to extract all href from a class in Python Selenium?


    References

    You can find a couple of relevant discussions in: