DEV Community

Cover image for Finding Elements in iframes with Selenium

Finding Elements in iframes with Selenium

razgandeanu profile image Klaus ・2 min read

Anyone who is using Selenium has encountered a scenario where they have to deal with an iframe.

There is no automatic way of detecting that the element you're looking for is inside an iframe.

The error message only says 'Element not found'.

You're the one who's going to have to look in the Browser Console and figure out that your element is inside an iframe.

Let's create a test for the Stripe Payments Demo which has an iframe.

I'll also be making some comparisons between Selenium and Endtest:

An iframe (inline frame) places another HTML document in a frame.

You need to change the focus of Selenium from one HTML document to another.

In our case, the only element which is inside the iframe is the Card input.

I used Python:


nameElement = driver.find_element_by_name("name")
emailElement = driver.find_element_by_name("email")
addressElement = driver.find_element_by_name("address")
cityElement = driver.find_element_by_name("city")
stateElement = driver.find_element_by_name("state")
zipElement = driver.find_element_by_name("postal_code")
countryElement = driver.find_element_by_name("country")
iframeElement = driver.find_element_by_name("__privateStripeFrame5")
cardElement = driver.find_element_by_name("cardnumber)
submitButton = driver.find_element_by_css_selector("#payment-form > button")

nameElement.send_keys("Klaus Werner")
addressElement.send_keys("Random Street")
cityElement.send_keys("San Francisco")
cardElement.send_keys("4111 1111 1111 1111")

Notice how I switched to the iframe before writing in the Card input?

And I also switched back to the main page after that.

It's a bit easier to deal with iframes if you're using Endtest:

Since you're planning to run that test multiple times, you should generate a random email address and store it in a variable.

You can even test that email with the Endtest Mailbox


Editor guide