selenium 获取td时出错:失效元素引用:元素未附加到页面文档

zqry0prt  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(176)

我是 selenium 编码的新手,我有下面的代码,我从表中获取值,它有多个页面,第一次,它从表中读取所有值,并控制移动到下一页,我得到错误陈旧的元素引用:元素未附加到页面文档,但当我调试代码时,我没有得到以下代码的任何错误,当我运行它时,它抛出一个错误,并在我定义tdCollection的行显示一个错误
请在这方面指导我。

var ReportCount = Convert.ToInt32(_driver.FindElement(By.Id("Reporter_TotalPages")).Text);

            for (int i = 0; i < ReportCount; i++)
            {
                IList<IWebElement> _records = (IList<IWebElement>)_driver.FindElements(By.XPath("//*[contains(@id,'ReportViewerControl')]//div//table//tbody//tr[position()>2]"));
                IList<IWebElement> tdCollection;
              
                for (int j = 0; j < _records.Count; j++)
                {
                   
                   tdCollection = _records[j].FindElements(By.TagName("td"));
                    
                    var Patientdemolist = new XPatientDemographicsList();
                    {
                        Patientdemolist.PatientID = tdCollection[0].Text;
                        Patientdemolist.LastName = tdCollection[1].Text;
                        Patientdemolist.FirstName = tdCollection[2].Text; 

                    };
                    PatientDemographicsList.Add(Patientdemolist);
                    tdCollection = null;
                }
                if (ReportCount - 1 > i)
                {
                    // For Next Page
                    _driver.FindElement(By.Id("Report_Next")).Click();
                } 
            }
nhaq1z21

nhaq1z211#

请尝试调整您的条件。

if (ReportCount - 1 > i)
{
    // For Next Page
    _driver.FindElement(By.Id("Report_Next")).Click();
    Thread.Sleep(5000)
}

您可能在页面完成加载之前就从.Click()方法获取了引用。如果这样做有效,您可以将测试细化为隐式等待/使用流畅等待,而不是等待5秒。https://www.selenium.dev/documentation/webdriver/waits/

相关问题