【发布时间】:2019-04-19 23:17:15
【问题描述】:
我有 Selenium 测试(用 Python 编写),它使用其 ID 查找 iframe,然后在 iframe 中查找按钮。 iframe 由浏览器扩展注入。这是 Python 代码:
id_ = "my-special-iframe"
driver.switch_to.frame(driver.find_element_by_id(id_))
polling.poll(
target=lambda:driver.find_elements_by_id("button")),
timeout=10,
step=1)
id 为“button”的元素存在于 iframe 内但不在 iframe 之外。
我观察到的是对 switch_to 的调用成功,但有一半的时间上下文仍然是 DOM 顶部的默认上下文。我知道这一点是因为driver.page_source 的结果会打印整个 DOM(就好像选择了默认上下文一样),而不是 iframe 的结果。此外,我可以根据需要多次调用switch_to(因为在主 DOM 中而不是 iframe 中,我可以选择 iframe)。因此,Selenium 找不到按钮元素。
以下是 Geckodriver 在 Selenium 无法进入 iframe 上下文的情况下的日志:
1542386220903 Marionette TRACE 0 -> [0,25,"WebDriver:FindElement",{"using":"xpath","value":"//iframe[@id='my-special-frame']"}]
1542386220906 Marionette TRACE 0 <- [1,25,null,{"value":{"element-6066-11e4-a52e-4f735466cecf":"47898438-5185-4e1e-ac19-c5220a6f8fcf"}}]
1542386220908 Marionette TRACE 0 -> [0,26,"WebDriver:SwitchToFrame",{"element":"47898438-5185-4e1e-ac19-c5220a6f8fcf"}]
1542386220910 Marionette TRACE 0 <- [1,26,null,{"value":null}]
1542386220912 Marionette TRACE 0 -> [0,27,"WebDriver:FindElement",{"using":"css selector","value":"#button"}]
1542386220914 Marionette TRACE 0 <- [1,27,{"error":"no such element","message":"Unable to locate element: #button","stacktrace":"WebDri ... entError@chrome://marionette/content/error.js:388:5\nelement.find/</<@chrome://marionette/content/element.js:339:16\n"},null]
除了最后找不到元素之外,在 Selenium 可以选择 iframe 上下文的情况下,日志看起来是一样的。
我使用 Chromedriver 和 Geckodriver 都看到了这一点。为什么 Selenium 有时不能切换到正确的上下文?当我打开 Chrome(或 Firefox)控制台时,我可以在那里看到 iframe 的内容,因此 Selenium 应该能够找到该元素。 Selenium 是否有切换到注入 iframe 的问题?
以前的答案涉及在 iframe 中查找元素,而无需先切换到 iframe。在这种情况下,我正在切换到 iframe,但即便如此我也没有得到正确的上下文。不知道为什么这被标记为重复。
【问题讨论】:
-
您是否尝试过为 Selenium 运行 JavaScript 执行程序以与按钮进行交互?我在尝试与 iframe 中的表单交互时遇到了类似的问题,但在框架之间切换对我来说效果很好。
-
您确定切换浏览上下文时 driver.page_source 会发生变化吗?
-
@Metareven 它没有。这就是问题所在:如果浏览上下文切换正确,我希望获得 iframe 的页面源,而不是整个页面。
-
@AlejandroHaro 有趣的想法 - 你有任何在 iframe 中选择按钮并单击它的示例代码吗?
-
@RobertHartley,我将添加我的 C# 代码。希望对您有所帮助。
标签: python selenium testing selenium-webdriver