Java 等待的结果并不总是一样的

Java 等待的结果并不总是一样的,java,selenium,Java,Selenium,我的直接等待有问题,不总是有效的。他们会随机失败,我不知道为什么。我正在命中未找到的元素或陈旧元素。我能做些什么使它们更可靠 public class FrameRegisterAccount extends BasicTests { // Generates Email String userName = ""+(int)(Math.random()*Integer.MAX_VALUE); String emailID = "Otto"+userName+"@gmail.com"; @Tes

我的直接等待有问题,不总是有效的。他们会随机失败,我不知道为什么。我正在命中未找到的元素或陈旧元素。我能做些什么使它们更可靠

public class FrameRegisterAccount extends BasicTests
{
// Generates Email
String userName = ""+(int)(Math.random()*Integer.MAX_VALUE);
String emailID = "Otto"+userName+"@gmail.com";

@Test (priority=1)
public void NewAccount() throws Exception {
    WebDriverWait wait = new WebDriverWait(driver, 15, 2500L);
    WebElement signButton = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//a[@class='button-sign']")));
    signButton.click();
    log.info("New Account Creation Screen Opened");

    // Fill out Form
    WebElement nameField = wait.until(ExpectedConditions.visibilityOfElementLocated(By.name("first_name")));
    nameField.sendKeys("Otto");

    driver.findElement(By.name("last_name")).sendKeys("Mation Tester");
    driver.findElement(By.name("phone_number")).sendKeys("555-555-3231");
    driver.findElement(By.name("listings")).sendKeys("4");

    // Enter Email and Password
    driver.findElement(By.xpath("//input[@name='email']")).clear();
    driver.findElement(By.xpath("//input[@name='email']")).sendKeys(emailID);
    driver.findElement(By.xpath("//input[@name='password']")).clear();
    driver.findElement(By.xpath("//input[@name='password']")).sendKeys("password");

    // Click buttons
    driver.findElement(By.xpath("//div[@class='input input-term']//div[@class='checkbox-icon']")).click();
    driver.findElement(By.xpath("//span[contains(text(),'Sign Up')]")).click();
    Thread.sleep(3000);
    log.info("New Account Created");
}

@Test (priority=2)
public void ChangePassword() {

    // Wait for Dashboard Button
    WebDriverWait wait = new WebDriverWait(driver, 15, 2500L);
    WebElement dashButton = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(@class,'success-dashboard')]")));
    dashButton.click();
    log.info("Go to Dashboard Button Pressed");

    // Change Password
    WebElement proNameX = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//div[@id='sidebar-top-item']")));
    proNameX.click();
    WebElement changePass = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//div[@id='nf-change-password-btn']")));
    changePass.click();

    //driver.findElement(By.xpath("//div[@id='nf-change-password-btn']")).click();
    driver.findElement(By.name("old_password")).sendKeys("password");
    driver.findElement(By.name("new_password")).sendKeys("wordpass");
    driver.findElement(By.name("new_password2")).sendKeys("wordpass");
    driver.findElement(By.xpath("//button[@type='button']")).click();
    log.info("Password Change Completed");
}
堆栈跟踪:

org.openqa.selenium.StaleElementReferenceException: 
stale element reference: element is not attached to the page document
  (Session info: headless chrome=72.0.3626.109)
  (Driver info: chromedriver=2.46.628388 (4a34a70827ac54148e092aafb70504c4ea7ae926),platform=Linux 4.14.88-88.76.amzn2.x86_64 x86_64) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 0 milliseconds
For documentation on this error, please visit: https://www.seleniumhq.org/exceptions/stale_element_reference.html
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'ip-172-31-36-12.us-west-2.compute.internal', ip: '172.31.36.12', os.name: 'Linux', os.arch: 'amd64', os.version: '4.14.88-88.76.amzn2.x86_64', java.version: '1.8.0_131'
Driver info: org.openqa.selenium.chrome.ChromeDriver
Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.46.628388 (4a34a70827ac54..., userDataDir: /tmp/.org.chromium.Chromium...}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:42199}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), rotatable: false, setWindowRect: true, strictFileInteractability: false, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 72.0.3626.109, webStorageEnabled: true}
Session ID: 1a448c188bc68362fa3dc7858ee770b3
    at registerAuto.FrameRegisterAccount.ChangePassword(FrameRegisterAccount.java:57)
堆栈2:

org.openqa.selenium.TimeoutException: 预期条件失败:等待元素可单击:By.xpath://div[@id='sidebar-top-item'](每隔2500毫秒尝试15秒) 构建信息:版本:“3.141.59”,修订版:“e82be7d358”,时间:“2018-11-14T08:17:03” 系统信息:主机:'ip-172-31-36-12.us-west-2.compute.internal',ip:'172.31.36.12',os.name:'Linux',os.arch:'amd64',os.version:'4.14.88-88.76.amzn2.x86_64',java.version:'1.8.0_131' 驱动程序信息:org.openqa.selenium.chrome.ChromeDriver 功能{AcceptSecureCerts:false,acceptSslCerts:false,applicationCacheEnabled:false,browserConnectionEnabled:false,browserName:chrome,chrome:{chromedriverVersion:2.46.628388(4a34a70827ac54…,userDataDir:/tmp/.org.chromium.chromium…),CSSSElectorEnabled:true,databaseEnabled:false,goog:chromeOptions:{debuggerAddress:localhost:42977},handlesAlerts:true,hasTouchScreen:false,javascriptEnabled:true,locationContextEnabled:true,mobileEmulationEnabled:false,nativeEvents:true,networkConnectionEnabled:false,pageLoadStrategy:normal,platform:LINUX,platformName:LINUX,proxy:proxy(),可旋转:false,setWindowRect:true,StrictFileInteractivity:false,takesHeapSnapshot:true,takesScreenshot:true,超时:{隐式:0,页面加载:300000,脚本:30000},意外行为:忽略,未处理PromptBehavior:ignore,版本:72.0.3626.109,启用WebStorage:true} 会话ID:7b255ab6a2cf5b58cf3919904e703b2a
至少StagingAutomation.FrameRegisterAccountStaging.ChangePassword(FrameRegisterAccountStaging.java:55)

当您尝试交互的元素不再位于dom中或已过时时,会出现StaleElementReference异常。因此,您需要刷新页面,然后再次获取该元素,该异常将正常工作


因此,请添加
driver.navigate().refresh()
在元素前面的一行代码,您将在该元素上获得异常,然后对该元素进行操作,它将正常工作。

当您尝试交互的元素不再在dom中或已过时时,会出现StaleElementReference异常。因此,您需要刷新页面,然后再次获取该元素,它将奥克


因此,请在获取异常的元素之前添加
driver.navigate().refresh();
一行代码,然后对该元素进行操作,这样就可以正常工作。

当我使用“WebDriverWait”时,我是否应该使用XPath?对于哪个元素,您将获得staleelementreference异常?大多数情况下是它的“/”按钮[包含(@class,'success-dashboard')]”此元素答案似乎有效:)感谢您的帮助。我确实有其他脚本遇到了“无此类元素:无法定位元素:”错误。我将在稍后发布该代码。如果您得到的是NoTouchElement,这意味着您的xpath不正确或您有一个iframe,请检查您是否在元素上方有一个iframe,并请接受答案。提前感谢!!我在使用“WebDriverWait”时是否应该不使用xpath?对于哪个元素,您将获得staleelementreference异常?大多数情况下,其“/”按钮[包含(@class,'success-dashboard')]”此元素答案似乎有效:)感谢您的帮助。我确实有其他脚本遇到“无此类元素:无法定位元素:”错误。我将在稍后发布该代码。如果您得到的是NoTouchElement,这意味着您的xpath不正确或您有一个iframe,请检查您是否在元素上方有一个iframe,并请接受答案。提前感谢!!如果元素过时,您不需要再次刷新页面…它已刷新。您只需要获取元素,而不是使用存储的变量引用。@JeffC实际上,网站也可以以不同的方式设计,我可以这样说,因为我处理的网站仅显示上次加载的结果中的值,并且当我使用
driver.navigate().back()返回该页时
即使在再次获取元素之后,元素也会显示StaleElementReference异常,因此在这种情况下,我必须在获取元素之前刷新页面。OP不会导航回。如果在
之后获取元素,则返回()
它们不应该过时。很可能是您的页面加载速度慢,或者在
.back()之后某些内容正在刷新
如果您等待,就不会有过时的元素。除非页面再次更改,否则元素在获取后没有理由过时。@JeffC是的,我可以看到他没有导航回页面,我只是给您举了一个例子,在再次获取元素并查看OP的代码之前,我必须刷新页面,我可以看到他正在再次获取元素,但仍然得到异常,这就是为什么我建议在再次获取元素之前刷新页面。如果元素已过时,则无需再次刷新页面……页面已刷新。您只需再次获取元素,而不必使用存储的变量引用。@JeffC实际上,网站也可以用不同的方式设计,我可以这么说,因为我处理的网站只显示上次加载的结果中的值,当我使用
driver.navigate().back()返回该页面时
即使在再次获取元素之后,元素也会显示StaleElementReference异常,因此在这种情况下,我必须在获取元素之前刷新页面。OP不会导航回。如果在
之后获取元素,则返回()
它们不应该过时。可能是您的页面加载速度慢,或者在
.back()
之后,如果您等待