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}">

And my attempted Python code is this:

#Import Selenium modules
from selenium import webdriver
from import By

driver = webdriver.Chrome()

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

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!

Hey @esbwebdesign i have the same issue did you find the solution ?

I never got this working, no. I think that it’s got to do with the way this particular website was being served–I could never get XPATH Helper to target anything inside the parent div either. I suspect if I really kept poking at it I might have been able to do a workaround by triggering JavaScript events instead, but it wasn’t worth the time it would have taken.