如何使用Xpath选择iframe中的元素?

Uri*_*Uri 18 python iframe selenium xpath

我想创建一个Selenium测试来测试我们的AOL邮件扩展.我设法登录AOL并撰写了一封电子邮件,但我还需要在编辑器中选择元素,这些元素位于iframe中.我检查了,甚至当编辑器打开时,以下测试失败:

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

我收到了错误AssertionError: 1 != 0.如何通过Xpath(或以任何其他方式使用Selenium)选择iframe和其他元素的主体?

dda*_*son 22

<iframe>在切换到它们之前,您无法遍历.你的xPath,

//iframe[@name='editor_body']//body[@contenteditable='true']
Run Code Online (Sandbox Code Playgroud)

将无法正常工作,因为<body>标记位于iFrame中,而iFrame不在当前上下文中.你需要先切换到它:

driver.switch_to.frame('editor_body')...
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,它的确有效!我用`self.driver.switch_to.frame(frame_reference = self.driver.find_element_by_xpath(x path ="// iframe [@ name ='editor_body']"))来做到这一点. (3认同)