【发布时间】:2017-12-18 15:46:54
【问题描述】:
我目前正在学习 Selenium,我学到了很多东西。社区说的一件事;是您需要尽可能避免 thread.sleep 。 Selenium 在替换中使用隐式和显式等待。是的,我理解这个概念。
最近我遇到了一个问题。这就是没有特定动作的情况;从登录页面转到另一个页面,而不使用 Thread.sleep(1000)。 Selenium 似乎太崩溃了:它找不到某个元素。我觉得这种行为很奇怪。所以我在想这个冲突发生了,因为登录页面首先要重定向到网站的主页并且没有 Thread.sleep(1000);它想去第二页,但登录页面拒绝它,因为它想先去主页。话虽如此,这就是为什么 Selenium 会崩溃,或者你们在下面的示例中看到和奇怪的代码使用了吗?
// Currently on a webpage
WebElement ui_login_button = wait.until(ExpectedConditions.presenceOfElementLocated(By.id("account-login-button")));
ui_login_button.click();
//After the click it logs in and redirects to a webpage
Thread.sleep(1000); // why sleep here? (without this Selenium crashes)
// Go to second page and perform actions
waitForLoad(driver);
driver.navigate().to(URL + "/mymp/verkopen/index.html");
/* -------------------------------------------------------------------
public void waitForLoad(WebDriver driver) {
ExpectedCondition<Boolean> pageLoadCondition = new
ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver driver) {
return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
}
};
//WebDriverWait wait = new WebDriverWait(driver, 30);
wait.until(pageLoadCondition);
}
抱歉解释,我尽力说清楚。英语不是我的母语。感谢您的帮助。
亲切的问候。
【问题讨论】:
-
Selenium crashes到底是什么意思?你看到有什么异常吗?你能粘贴错误堆栈跟踪吗? -
DebanjanDB 就像我说的那样。它引发了一个异常,即在网页上找不到该元素。我还解释了我对此的想法。我通过在两者之间睡觉来解决它。然后它确实找到了它,但它不是解决这个问题的优雅解决方案。
标签: java multithreading selenium webdriver webdriverwait