我正在尝试等待 Selenium 切换不断变化的帧,然后再等待另一个元素。即
var wait = new WebDriverWait(driver, 15);
wait.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.Id("frameA"));
var wait2 = new WebDriverWait(driver, 15);
// wait for element within frameA to exist
wait2.Until(ExpectedConditions.ElementExists(By.Id("elementA")));
如果我在第二次等待之前加入一个简单的 Thread.Sleep(1000);
它会正常运行,但如果没有它,我会收到以下错误:
'unknown error: unhandled inspector error: {"code":-32000,"message":"Cannot find context with specified id"}
enter code here
有没有更好的方法来等待框架上下文切换完成,然后再等待该框架内的元素被填充?
最佳答案
您需要考虑几件事:
切换到框架的代码行看起来很完美,不会引发任何错误:
var wait = new WebDriverWait(driver, 15);
wait.Until(ExpectedConditions.FrameToBeAvailableAndSwitchToIt(By.Id("frameA"));
在下一行中,您尝试了 ExpectedConditions 方法 ElementExists。根据 API 文档 ElementExists
方法定义为:
An expectation for checking that an element is present on the DOM of a page. This does not necessarily mean that the element is visible.
Selenium 无法与元素交互,直到元素可见。因此你需要使用方法 ElementIsVisible
如下:
var wait2 = new WebDriverWait(driver, 15);
wait2.Until(ExpectedConditions.ElementIsVisible(By.Id("elementA")));
在这里您可以找到关于 Ways to deal with #document under iframe 的详细讨论。
关于c# - 如何在定位元素之前等待框架加载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49677267/