Selenium 等待不等待元素可点击

J. *_*han 5 c# selenium wait

我有一个动态加载的页面并包含一个按钮。我正在尝试等待使用 C# 绑定使用 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();
Run Code Online (Sandbox Code Playgroud)

虽然这不起作用。click 事件永远不会被触发。selenium 脚本不会抛出异常,提醒 ID 为“addInspectionButton”的元素不存在。它只是无法点击它。如果我在等待语句和我获得按钮元素句柄的行之间添加一个 Thread.Sleep(3000) ,它会起作用。

我在这里没有正确使用 ExpectedConditions.ElementToBeClickable 吗?

J. *_*han 2

原来按钮动态添加到页面后,就给按钮绑定了一个事件。所以按钮被点击但什么也没有发生。代码中放置的睡眠线程只是为客户端事件提供了绑定时间。

我的解决方案是单击按钮,检查预期结果,然后如果预期结果不在 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
        }
Run Code Online (Sandbox Code Playgroud)