【问题标题】:How do I select elements inside an iframe with Xpath?如何使用 Xpath 在 iframe 中选择元素?
【发布时间】:2015-05-03 02:34:39
【问题描述】:

我想创建一个 Selenium 测试来使用 AOL 邮件测试我们的扩展。我设法登录到 AOL 并撰写了一封电子邮件,但我还需要在 iframe 内的编辑器中选择元素。我检查过,即使打开编辑器,以下测试也失败了:

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

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

【问题讨论】:

  • 您是否尝试过使用.switch_to().frame(element)
  • @MarkRowlands 谢谢,它有效!但是self.driver.switch_to.frame(frame_reference=self.driver.find_element_by_xpath(xpath="//iframe[@name='editor_body']"))

标签: python selenium iframe xpath


【解决方案1】:

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

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

将不起作用,因为 <body> 标记位于 iFrame 中,而 iFrame 不在当前上下文中。你需要先切换到它:

driver.switch_to.frame('editor_body')...

【讨论】:

  • 谢谢,它有效!我用self.driver.switch_to.frame(frame_reference=self.driver.find_element_by_xpath(x‌​path="//iframe[@name='editor_body']")) 做到了
  • 我将如何使用 selenium 节点执行此操作?
  • 无论你是在本地运行,还是使用节点——结果都是一样的。
  • 实际上可以通过将xpath的范围设置为iframe的contentDocument属性as explained in this answer来避免switch_to_frame调用。
猜你喜欢
  • 2013-01-05
  • 2019-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多