Selenium 陈旧元素参考:元素未附加到页面文档

Selenium stale element reference: element is not attached to the page document

当我尝试点击下拉列表 ID 时出现此错误:

stale element reference: element is not attached to the page document

我正在考虑使用此代码:

boolean staleElement = true;
        while(staleElement)
        {
            try{
                WebDriverWait wait = new WebDriverWait(driver, 20);
                WebElement element = driver.findElement(By.id(dropDownId));
                wait.until(ExpectedConditions.elementToBeClickable(element));
                element.click();
                staleElement = false;
            }
            catch(StaleElementReferenceException e)
            {
                staleElement = true;
                Thread.sleep(200);
            }
        }

有没有什么方法可以防止无限循环或在出现此异常后点击 id 的更好方法?

总的来说你的代码还是不错的。为避免无限循环,您可以在此处添加某种计数器,以防万一尝试单击该元素失败 10 次以致测试失败。
如果您在 try 块中遇到 Element is not clickable at point 异常,您可以尝试使用 visibilityOfElementLocated Expected Conditin 而不是 elementToBeClickable.
如果这仍然不够,您可以在 wait.until(ExpectedConditions.visibilityOfElementLocated(element));element.click(); 命令之间添加一个短暂的延迟,让元素在单击元素之前最终呈现在页面上。