我有一个动态加载的页面,其中包含一个按钮。我正在尝试等待按钮可用,以便使用 C# 绑定(bind)用 selenium 单击。我有以下代码:
WebDriverWait wait = new WebDriverWait(Driver.Instance, TimeSpan.FromSeconds(30));
wait.Until(ExpectedConditions.ElementToBeClickable(By.Id("addInspectionButton")));
var button = Driver.Instance.FindElement(By.Id("addInspectionButton"));
button.Click();
虽然这不起作用。永远不会触发点击事件。 selenium 脚本不会抛出异常,警告 ID 为“addInspectionButton”的元素不存在。它只是无法单击它。如果我在等待语句和我获得按钮元素句柄的行之间添加一个 Thread.Sleep(3000),它就可以工作。
我在这里没有正确使用 ExpectedConditions.ElementToBeClickable 吗?
最佳答案
事实证明,在按钮被动态添加到页面后,事件被绑定(bind)到按钮。所以按钮被点击但没有发生任何事情。放置在代码中的 sleep 线程只是为客户端事件绑定(bind)时间。
我的解决方案是单击按钮,检查预期结果,然后如果预期结果不在 DOM 中则重复此操作。
因为预期的结果是打开一个表单,所以我像这样轮询 DOM:
button.Click();//click button to make form open
var forms = Driver.Instance.FindElements(By.Id("inspectionDetailsForm"));//query the DOM for the form
var times = 0;//keep tabs on how many times button has been clicked
while(forms.Count < 1 && times < 100)//if the form hasn't loaded yet reclick the button and check for the form in the DOM, only try 100 times
{
button.Click();//reclick the button
forms = Driver.Instance.FindElements(By.Id("inspectionDetailsForm"));//requery the DOM for the form
times++;// keep track of times clicked
}
关于c# - Selenium Wait 不等待元素可点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31614205/