1

我是 Selenium 的新手,对 Java 也很陌生。我是一名测试人员,而不是开发人员,所以我正在尝试逐渐将我的 Selenium IDE 脚本转换为更强大和“适当”的东西。不幸的是,我正在努力完成一项相当基本的任务。网页加载后,我想单击一个按钮。这在 Selenium IDE 中运行良好,但前提是我将速度设置为“慢”。

我可以使用以下代码使其工作,但前提是我包含 thread.sleep 行。我读过这不是一个好主意,所以我正在尝试使用 webDriverWait 实现更智能的东西。

public class mytestclass {

    private WebDriver driver;
    private String baseUrl;

    @Before
    public void setUp() throws Exception {
        driver = new FirefoxDriver();
        baseUrl = "";
        driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
    }


    @Test
    public void test1() throws Exception {
        driver.get(baseUrl + "file:///C:/_VM/testpage.html");
        WebDriverWait wait = new WebDriverWait(driver, 10);
        wait.until(ExpectedConditions.elementToBeClickable(By.id("button_X")));
        //Thread.sleep(2000);
        driver.findElement(By.id("button_X")).click();    
     }

}

因此,在执行 thread.sleep 行时它起作用的事实让我相信当按钮实际上没有准备好时,wait.until 行返回 true。我还尝试将 ExpectedConditions 切换到其他标识符,例如 visibilityOfElementLocated(By locator) 和 presenceOfElementLocated(By locator),但它们的行为方式也相同。

我在这里做错了吗?还有什么我可以尝试的吗?

恐怕我无法链接到该网站,因为它与工作有关。它确实会读取大量图像并在启动时运行大量 javascript,因此确实需要一些时间才能开始,但这就是为什么我要添加等待逻辑!

感谢您的任何建议。

4

1 回答 1

1

您的网站启动是否涉及 jQuery?如果是这样,你可以试试这个。我发现它对我的测试很有帮助。它在 C# 中,但我相信你可以将它转换为 java。

等到 jQuery 准备好:

IWait<IWebDriver> wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(WAITFORELEMENT_TIMEOUT));
wait.Until(d => (bool)(d as IJavaScriptExecutor).ExecuteScript("return jQuery.active == 0"));
于 2014-10-22T04:32:06.787 回答