Home > Enterprise >  How to identify the iframe using Selenium?
How to identify the iframe using Selenium?

Time:03-19

HTML:

<iframe allowpaymentrequest="true" allowtransparency="true" src="https://shopify.wintopay.com/
cd_frame_id_="ca9e4ad6a1559de159faff5c1f563d59"
name="WinCCPay"
id="win-cc-pay-frame" 

I'm trying to input text in a CC field. Apparently its in an iframe I picked the last one in the HTML and tried to select it from the identifiers above but I keep getting the element couldn't be found

iframe= wd.find_element_by_id("win-cc-pay-frame")    

wd.switch_to.frame(iframe)

The frame is currently being shown in the browser so no need for implicit wait.

CodePudding user response:

To identify the <iframe> so you have to:

  • Induce WebDriverWait for the desired frame to be available and switch to it.

  • You can use either of the following Locator Strategies:

    • Using CSS_SELECTOR:

      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.CSS_SELECTOR,"iframe#win-cc-pay-frame[name='WinCCPay'][src^='https://shopify.wintopay.com']")))
      
    • Using XPATH:

      WebDriverWait(driver, 20).until(EC.frame_to_be_available_and_switch_to_it((By.XPATH,"//iframe[@id='win-cc-pay-frame' and @name='WinCCPay'][starts-with(@src, 'https://shopify.wintopay.com')]")))
      
  • 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
    

CodePudding user response:

The problem can be that the name and id of the element are dynamic and change for each unique checkout window? Can you check if adding class attribute at iframe tag and find element by this attribute?

It must be similar to:

iframe = wd.find_element_by_class_name('card-pay-iframe')
wd.switch_to.frame(iframe)
...
wd.switch_to.default_content()

good coding! ¯_(ツ)_/¯

  • Related