我有一個 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 ;
}
}
}
uj5u.com熱心網友回復:
該運算式tdCollection = row.FindElements(By.TagName"tr")正在拋出,StaleElementReference因為它試圖訪問row經過幾次迭代后已經過時的元素,這可能是因為 HTML 元素rows表示已更改。
您應該嘗試動態迭代表,而不是獲取可能如您描述的那樣更改的固定行串列。
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一個將被檢查的布爾標志。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/402968.html
標籤:
