我发现了问题...:selenium WebDriver StaleElementReferenceException
*This may be caused because the page isn't loaded completely when the code starts or changes when the code is executed. You can either try to wait a little longer for the element or catch the StaleReferenceException and try again finding the div and the span.*
我的代码:(在每个字段之前调用这些函数)
/**
* Handle StaleElementReferenceException
* @param elementXpath
* @param timeToWaitInSec
*/
public void staleElementHandleByXpath(String elementXpath, int timeToWaitInSec) {
int count = 0;
while (count < 10) {
try {
WebElement slipperyElement = driver.findElement(By.xpath(elementXpath));
if (slipperyElement.isDisplayed()) {
slipperyElement.click(); // may throw StaleElementReferenceException
}
count = count + 10;
} catch (StaleElementReferenceException e) {
count = count + 1; // try again
} catch (ElementNotVisibleException e) {
count = count + 10; // get out
} catch (Exception e) {
count = count + 10; // get out
} finally {
// wait X sec before doing the action
driver.manage().timeouts().implicitlyWait(timeToWaitInSec, TimeUnit.SECONDS);
}
}
}
/**
* Wait till the document is really ready
* @param js
* @param timeToWaitInSec
*/
public void waiTillDocumentReadyStateComplete(JavascriptExecutor js, int timeToWaitInSec) {
Boolean ready = false;
int count = 0;
while (!ready && count < 10) {
ready = (Boolean) js.executeScript("return document.readyState == 'complete';");
// wait X sec before doing the action
driver.manage().timeouts().implicitlyWait(timeToWaitInSec, TimeUnit.SECONDS);
count = count + 1;
}
}
使用单引号
'
而不是 "
。所以
String fieldXpath = "//input[@id='signin_password']";