无法找到页面元素,因为 "Element is no longer valid"
Unable to find page elements because "Element is no longer valid"
Selenium 在查找页面上的元素时抛出异常。它抱怨 "Element is no longer valid".
例如,在一个带有下拉列表的页面上,当我 select 一个选项时,我需要找到 table 个选项。对于前几个选项,我找到了 table,但最终搜索元素会导致异常。
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(25));
IList<IWebElement> tableTRCollection = null;
IList<IWebElement> tableTDCollection;
bool exist = false;
while(!exist)
{
try
{
tableTRCollection = driver.FindElements(By.XPath("//table[@id='t1']/tbody/tr"));
exist = true;
}
catch(Exception ex)
{
Wait(1);
}
}
for (int k = 0; k < tableTRCollection.Count; k++)
{
tableTDCollection = tableTRCollection[k].FindElements(By.TagName("td")); // -> Element is no longer valid
}
我对每个下拉选项循环一次整个代码块。前几次一切正常。下次我看到这个:
- 它退出 while 循环(它找到了 table 和
tableTRCollection
)
- 进入for循环(
tabletTRCollection
至少包含一行)
tableTRCollection[k].FindElements(By.TagName("td"))
抛出 "Element is no longer valid" 异常。
我尝试了 Selenium 的等待函数,但结果是一样的。
是什么导致 tableTRCollection[k]
元素不再有效?页面没有变化。
在从下拉列表中进行选择会导致 DOM 发生变化的页面(javascript 魔术、AJAX 请求等),那么您在选择后立即找到的元素可能当您使用它们来查找更多元素时,它们已经消失了。简单的时间表可能是:
- Select 项来自下拉列表
- 查找元素 X
- 做一些工作
- DOM 变化
- 致电
X.FindElement(...)
- 发生异常。
页面可能看起来没有变化,但 Selenium 对所有 DOM 变化都很敏感,并且会抱怨。
您通常可以通过直接使用 driver.FindElements()
而不是 element.FindElements()
来解决这个问题。如果您正在使用 By.CssSelector()
或 By.Xpath()
,您可能必须聪明点。
Selenium 在查找页面上的元素时抛出异常。它抱怨 "Element is no longer valid".
例如,在一个带有下拉列表的页面上,当我 select 一个选项时,我需要找到 table 个选项。对于前几个选项,我找到了 table,但最终搜索元素会导致异常。
driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(25));
IList<IWebElement> tableTRCollection = null;
IList<IWebElement> tableTDCollection;
bool exist = false;
while(!exist)
{
try
{
tableTRCollection = driver.FindElements(By.XPath("//table[@id='t1']/tbody/tr"));
exist = true;
}
catch(Exception ex)
{
Wait(1);
}
}
for (int k = 0; k < tableTRCollection.Count; k++)
{
tableTDCollection = tableTRCollection[k].FindElements(By.TagName("td")); // -> Element is no longer valid
}
我对每个下拉选项循环一次整个代码块。前几次一切正常。下次我看到这个:
- 它退出 while 循环(它找到了 table 和
tableTRCollection
) - 进入for循环(
tabletTRCollection
至少包含一行) tableTRCollection[k].FindElements(By.TagName("td"))
抛出 "Element is no longer valid" 异常。
我尝试了 Selenium 的等待函数,但结果是一样的。
是什么导致 tableTRCollection[k]
元素不再有效?页面没有变化。
在从下拉列表中进行选择会导致 DOM 发生变化的页面(javascript 魔术、AJAX 请求等),那么您在选择后立即找到的元素可能当您使用它们来查找更多元素时,它们已经消失了。简单的时间表可能是:
- Select 项来自下拉列表
- 查找元素 X
- 做一些工作
- DOM 变化
- 致电
X.FindElement(...)
- 发生异常。
页面可能看起来没有变化,但 Selenium 对所有 DOM 变化都很敏感,并且会抱怨。
您通常可以通过直接使用 driver.FindElements()
而不是 element.FindElements()
来解决这个问题。如果您正在使用 By.CssSelector()
或 By.Xpath()
,您可能必须聪明点。