在Selenium webdriver

时间:2016-04-07 23:48:01

标签: 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 exists')
webui.driver.find_element_by_link_text('Test_string_for_profile').click()

通过hamcrest完成的断言通过。每当执行第三行时,都会引发异常。我知道页面刷新速度非常快(它必须,并且我无法控制刷新的频率)。

1 个答案:

答案 0 :(得分:0)

我从博客得到了这个答案,验证它是否有用。 C#中的代码

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;
    }

在C#中我们有等待,不知道phyton

new WebDriverWait(Drivers._driverInstance, new TimeSpan(0, 0, 30)).Until(ExpectedConditions.StalenessOf(_webElement));