How do I select elements inside an iframe with Xpath?

45,933

You cannot traverse through <iframe>'s until switching to them. Your xPath,

//iframe[@name='editor_body']//body[@contenteditable='true']

will not work because the <body> tag is within an iFrame, which is not in the current context. you need to switch to it first:

driver.switch_to.frame('editor_body')...
Share:
45,933

Related videos on Youtube

Uri
Author by

Uri

I'm a software programmer and sometimes an entrepreneur. I recently launched Speedy Match - a new matching/dating website for singles in Hebrew and English. Speedy Match is available for Speedy Net users. I also launched Speedy Net in Python and Django. I also created Speedy Composer, Speedypedia and Speedy Whois. All these projects are free software &amp; open source. My personal homepage (with links to my profile on GitHub, LinkedIn and more).

Updated on March 03, 2020

Comments

  • Uri
    Uri over 4 years

    I want to create a Selenium test to test our extensions with AOL mail. I managed to login to AOL and compose an email, but I also need to select elements inside the editor, which is inside an iframe. I checked and even when the editor is open the following test fails:

    self.assertEqual(first=1, second=len(self.driver.find_elements_by_xpath(xpath="//iframe[@name='editor_body']//body[@contenteditable='true']")))
    

    I get the error AssertionError: 1 != 0. How do I select the body of the iframe and other elements by Xpath (or in any other way with Selenium)?

    • Mark Rowlands
      Mark Rowlands over 9 years
      Have you tried using the .switch_to().frame(element)?
    • Uri
      Uri over 9 years
      @MarkRowlands Thank you, it works! But with self.driver.switch_to.frame(frame_reference=self.driver.find‌​_element_by_xpath(xp‌​ath="//iframe[@name=‌​'editor_body']"))
  • Uri
    Uri over 9 years
    Thank you, it works! I did it with self.driver.switch_to.frame(frame_reference=self.driver.find‌​_element_by_xpath(x‌‌​​path="//iframe[@nam‌​e='editor_body']"))
  • Jeremy Moritz
    Jeremy Moritz over 8 years
    how would i do this with selenium node?
  • ddavison
    ddavison over 8 years
    whether you are running locally, or using a node - the result is the same.
  • mMontu
    mMontu over 6 years
    Actually it is possible to avoid the switch_to_frame call by setting the scope of the xpath to the iframe's contentDocument property as explained in this answer.