c# Selenium Webdriver -- 遍历 table 行并单击每行中的按钮

c# Selenium Webdriver -- Iterating through table rows and click button in each row

我在第二次遍历 table 行时收到以下错误,其中有一个活动的删除按钮。
"Result StackTrace: OpenQA.Selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document"

            IWebElement baseTable = Browser.Driver.FindElement(By.XPath("//*[@id='approvalsGrid']/table/tbody"));
            ICollection<IWebElement> delButton = baseTable.FindElements(By.XPath("//*[@class = 'k-grid-remove lnkDelete']"));
            foreach (var button in delButton)
            {
                button.Click();
                WaitForAjax();
                //2nd delete button in popup
                Browser.Driver.FindElement(By.XPath("//a[text() = ' Delete']")).Click(); 
                WaitForAjax();
            }

任何帮助将不胜感激。

当您在一个按钮上单击 删除 时,按钮集合似乎变得陈旧,因此删除条目后该集合将不再可用。

在这种情况下,您可能需要更改策略以在删除按钮后查找新的删除按钮。这样的事情可能会奏效:

By delButtonsBy = By.XPath("//*[@class = 'k-grid-remove lnkDelete']");
bool delButtonExists = baseTable.FindElements(delButtonsBy).Count > 0;

while (delButtonExists)
{
    baseTable.FindElements(delButtonsBy)[0].Click();
    WaitForAjax();
    //2nd delete button in popup
    Browser.Driver.FindElement(By.XPath("//a[text() = ' Delete']")).Click();
    WaitForAjax();
    delButtonExists = baseTable.FindElements(delButtonsBy).Count > 0;
}    

这更昂贵,因为您必须一遍又一遍地查找集合,但无论如何您都必须这样做才能获得第一个元素,因为每次您访问时页面结构都会发生变化并且集合已过时删除一个。

您可以进一步更改它以只检查第一个元素而不是整个集合,这可能会略微提高性能,但无论哪种方式都应该很快,除非您谈论的是非常大量的按钮.