Samuel Okasia
Samuel Okasia

Reputation: 105

How to locate an element inside iFrame using Selenium and Python

This is the ifram source code:

<iframe sandbox="allow-scripts allow-same-origin" class="credit-card-iframe mt1 u-full-width prl2-sm" src="https://paymentcc.nike.com/services/default?id=3f42d8c5-74ee-4d08-95aa-bb6ea4949f9f&amp;ctx=checkout&amp;language=en-GB&amp;maskerEnabled=true" frameborder="0" scrolling="no" xpath="1"></iframe>

This is the element i want;

<input maxlength="20" class="mod-ncss-input ncss-input pt2-sm pr4-sm pb2-sm pl4-sm" id="creditCardNumber" onautocomplete="off" value="" type="tel" tabindex="0" data-shortname="cc">

This is my code:

browser.switch_to.frame(browser.find_element_by_xpath("//iframe[@class='credit-card-iframe mt1 u-full-width prl2-sm']"))
browser.implicitly_wait(10)
card = browser.find_element_by_xpath("//input[@id='creditCardNumber']")
card.send_keys("35663565444")

This is the error:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"//input[@id='creditCardNumber']"}

Also if I have to scroll on a page to see something can the element still be picked up thanks.

Upvotes: 3

Views: 3547

Answers (2)

Hrisimir Dakov
Hrisimir Dakov

Reputation: 587

You aren't properly waiting for the element. Do not ever use implicit waits, but instead try the followig:

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support.expected_conditions import visibility_of_element_located

CARD_INPUT_LOCATOR = By.ID, "creditCardNumber"
card_input = WebDriverWait(browser, 20).until(visibility_of_element_located(CARD_INPUT_LOCATOR))
card_input.send_keys("35663565444")

This should solve your problem.

Upvotes: 0

undetected Selenium
undetected Selenium

Reputation: 193058

As the the desired element is within an <iframe> so to invoke click() on the element 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 the following Locator Strategies::

    • Using XPATH:

      WebDriverWait(driver, 10).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@sandbox='allow-scripts allow-same-origin' and contains(@class, 'credit-card-iframe')]")))
      WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='creditCardNumber' and @data-shortname='cc']"))).send_keys("35663565444")
      
    • 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 relevant discussion in:

Upvotes: 2

Related Questions