循环访问表最终会引发过时元素异常



我有一个Selenium C#脚本,它循环访问表并收集行中的所有数据。但是,在我第三次向下翻阅表格后,我收到一个过时的元素异常。需要注意的一点是,此表位于 Iframe 中,除非您向下滚动该表,否则不会加载数据。我通过收集TD来解决这个问题,一旦我收到一个空白TD,然后向下翻页到表中的下一组数据。如何防止tdCollection = row.FindElements(By.TagName"tr")过时?

do
{
IList<IWebElement> tdCollection;
IWebElement table = driver.FindElement(By.Id("isc_Jtable"));
var rows = table.FindElements(By.TagName("tr"));
foreach (var row in rows)
{
tdCollection = row.FindElements(By.TagName("td"));
if (tdCollection[0].Text == "")
{
CurrentFrame.ActiveElement().SendKeys(Keys.PageDown);
}
else
{
Logger.WriteLog(logName, String.Format("{1}{0}", " PCI ID: " + tdCollection[0].Text, DateTime.Now.ToLocalTime()));
tdCount++;
}
}
}
表达式tdCollection = row.FindElements(By.TagName"tr")

抛出StaleElementReference,因为它试图访问经过几次迭代后已经过时的row元素,可能是因为rows表示的HTML元素已更改。

您应该尝试动态遍历表,而不是获取可能如您所描述的那样更改的固定行列表。

IWebElement table = driver.FindElement(By.Id("isc_Jtable"));
int tableRowIndex = 1;
while (true) {
try {
var tableRow = table.FindElement(By.Xpath("tr[" + tableRowIndex + "]"));
tableRowIndex++;
IList<IWebElement> tdCollection = tableRow.FindElements(By.TagName("td"))
// Do something with tdCollection
}
catch (NoSuchElementException ex) {
// Last iteration
break;
}
}

您可以看到我只保留对"活动"行的引用,当我处理完其数据时,我会找到下一个。

此外,如果您不喜欢while (true),您可以将break换成将被检查的布尔标志。

最新更新