Issues with targeting Iframe in Python with Selenium

I am trying to automate an annoying process at work by using Python to do the actual data entry. I’m having a hard time switching to an Iframe; I am getting the ‘element not found’ error.

The relevant HTML code from this page is:

<div id="contentFrames">
	<iframe id="contentFrame21" src="{some link}">
	</iframe>
</div>

And my attempted Python code is this:

#Import Selenium modules
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()

iframe = driver.find_element(By.XPATH, "//iframe[@id='contentFrame29']")
driver.switch_to.frame(iframe)

What I have tried:

  • I know my target Iframe isn’t inside any other Iframe. I can target its parent div using:
driver.find_element(By.XPATH, "//div[@id='contentFrames']")
  • I have tried using By.ID instead of By.XPATH
  • I have tested the syntax by making a very simple HTML page and using the same syntax to target an Iframe on that page
  • I cannot just go to the source of the Iframe because it bounces me back to the login page when I try

Possible Theories

  • I wonder if the page isn’t treating this Iframe like an Iframe for some reason? If so, I’m not sure how to handle that.

Hello @esbwebdesign,

I tested your code by changing contentFrame29 to contentFrame21 and it worked.

Could that be the problem?

Sorry, that was a transcription error when copying some simplified code. It matches up in my original and doesn’t work.

I suspect it has something to do with how this web page is rendering–I ended up just doing the data entry. I do appreciate your help though!