我有 Selenium 测试(用 Python 编写)使用其 ID 查找 iframe,然后在 iframe 中查找按钮。 iframe 由浏览器扩展注入(inject)。这是 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 找不到按钮元素。
这是在 Selenium 无法进入 iframe 上下文的情况下来自 Geckodriver 的日志:
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 在切换到注入(inject)的 iframe 时有问题吗?
以前的答案涉及在 iframe 中查找元素,而无需先切换到 iframe。在这种情况下,我正在切换到 iframe 但即便如此我也没有获得正确的上下文。不知道为什么这被标记为重复。
最佳答案
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("formstack")));
driver.SwitchTo().Frame("formstack");
var FirstName = driver.FindElement(By.CssSelector("#field58374948"));
FirstName.Click();
FirstName.SendKeys("Alejandro");
driver.SwitchTo().defaultContent();
关于python - Selenium 无法选择 iframe 的上下文(间歇性地),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53343417/