'How to identify the iframe using Selenium?

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.



Solution 1:[1]

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
    

Solution 2:[2]

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! ¯_(?)_/¯

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Pedring Coding