Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 980
Samuel Okasia Avatar asked Apr 11 '26 22:04

Samuel Okasia


1 Answers

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:

  • Ways to deal with #document under iframe
like image 140
undetected Selenium Avatar answered Apr 14 '26 14:04

undetected Selenium