loading...
Cover image for Finding Elements in iframes with Selenium
Endtest

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:

driver.get("https://stripe-payments-demo.appspot.com")

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")
emailElement.send_keys("klaus.werner@example.com")
addressElement.send_keys("Random Street")
cityElement.send_keys("San Francisco")
stateElement.send_keys("CA")
zipElement.send_keys("94107")
countryElement.select_by_value("US")
driver.switch_to.frame(iframeElement)
cardElement.send_keys("4111 1111 1111 1111")
driver.switch_to.default_content()
submitButton.click()

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

Posted on by:

razgandeanu profile

Klaus

@razgandeanu

Developer. Passionate about Automated Testing.

Endtest

We're a cool startup! Our platform is all about Codeless Automated Testing. Create and run your automated tests in our cloud infrastructure.

Discussion

markdown guide