Python 在Selenium webdriver上避免StaleElementReferenceException的最佳方法
我正在为一个web界面编写一些测试,该界面不断刷新,刷新速度很快。避免获取StaleElementReferenceException的最佳方法是什么?通常我需要检查页面是否有基于ID的元素。如果找到,则单击该元素(可以是按钮或超链接等) 编辑:代码示例Python 在Selenium webdriver上避免StaleElementReferenceException的最佳方法,python,selenium,selenium-webdriver,Python,Selenium,Selenium Webdriver,我正在为一个web界面编写一些测试,该界面不断刷新,刷新速度很快。避免获取StaleElementReferenceException的最佳方法是什么?通常我需要检查页面是否有基于ID的元素。如果找到,则单击该元素(可以是按钮或超链接等) 编辑:代码示例 profile = webui.driver.find_element_by_link_text('Test_string_for_profile') assert_that(profile, not_none(), 'Profile exis
profile = webui.driver.find_element_by_link_text('Test_string_for_profile')
assert_that(profile, not_none(), 'Profile exists')
webui.driver.find_element_by_link_text('Test_string_for_profile').click()
通过hamcrest完成的断言通过。每当执行第三行时,就会引发异常。我知道页面刷新得很快(必须如此,我无法控制刷新的频率)。我从博客上得到了这个答案,请验证它是否有用。C代码#
这实际上是特定于用例的。请提供迄今为止您拥有的代码,如果可能,请提供指向您正在使用的网页的链接。您不能使用标准的try/except块吗?
public static Boolean RetryingFind(By by)
{
Boolean result = false;
int attempts = 0;
while (attempts < 2)
{
try
{
Drivers._driverInstance.FindElement(by);
result = true;
break;
}
catch (StaleElementReferenceException)
{
new WebDriverWait(Drivers._driverInstance, new TimeSpan(0, 0, 0, 0, 10));
}
attempts++;
}
return result;
}
new WebDriverWait(Drivers._driverInstance, new TimeSpan(0, 0, 30)).Until(ExpectedConditions.StalenessOf(_webElement));