2015-09-25 55 views
1

虽然关于JavaScript组件即时得到点击:元件不连接到页面文档

org.openqa.selenium.StaleElementReferenceException:陈旧元件 参考:元件未连接到页面文档

解决这个问题的一种方法是在短时间内停止脚本: Thread.sleep(200);

我有我的10秒implicitlyWait集,我觉得有wasnt这样的问题与旧硒

但有没有其他办法可以做到在全球范围呢?

但是在这中间我已经把睡觉的,使其工作:

driver.findElement(By.cssSelector("button.btn.btn-default")).click(); 
Thread.sleep(200); 
     driver.findElement(By.xpath("//div[@id='content']/div/form")).click(); 
Thread.sleep(200); 
     driver.findElement(By.linkText("Order")).click(); 

回答

1

在我的示例中将getWebDriver()替换为您的驱动器实例。

最佳做法是首先声明&验证是否存在该特定的 元素。如果你看到函数 assertAndVerifyElement()---它连续检查5 秒的元素,然后相应地断言它。

package com.stackoverflow; 

import org.openqa.selenium.By; 
import org.testng.Assert; 
import org.testng.annotations.Test; 

import com.services.Init; 

public class Issue3 extends Init { 

    @Test 
    public void solutionOfIssue() throws InterruptedException { 

     /* 
     * The best thing is to first assert & verify that, that particular 
     * element is present or not. if you see function 
     * assertAndVerifyElement() --- it continuously checks for element for 5 
     * secs and then assert it accordingly. 
     */ 

     assertAndVerifyElement(By.cssSelector("button.btn.btn-default")); 
     getWebDriver().findElement(By.cssSelector("button.btn.btn-default")).click(); 

     assertAndVerifyElement(By.xpath("//div[@id='content']/div/form")); 
     getWebDriver().findElement(By.xpath("//div[@id='content']/div/form")).click(); 

     assertAndVerifyElement(By.linkText("Order")); 
     getWebDriver().findElement(By.linkText("Order")).click(); 

    } 

    public void assertAndVerifyElement(By element) throws InterruptedException { 
     boolean isPresent = false; 

     for (int i = 0; i < 5; i++) { 
      try { 
       if (getWebDriver().findElement(element) != null) { 
        isPresent = true; 
        break; 
       } 
      } catch (Exception e) { 
       // System.out.println(e.getLocalizedMessage()); 
       Thread.sleep(1000); 
      } 
     } 
     Assert.assertTrue(isPresent, "\"" + element + "\" is not present."); 
    } 

} 

希望这会为你工作。:)

1

为了避免这种情况,你应该重新定位的元素。获得元素后,其Java对象的引用可能会变陈旧。再次执行如下操作: WebElement element = WebDriver.findElement(By by)

编辑:对于您的例子试试这个

driver.findElement(By.cssSelector("button.btn.btn-default")).click(); 
//30s timeout, use timeout not sleep 
WebDriverWait wait = new WebDriverWait(driver, 30); 
By xpath = By.xpath("//div[@id='content']/div/form") 
//wait for element to be clickable, then click 
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(xpath)); 
element.click(); 
1

你的问题是,你需要构建测试用例更好的和/或缺乏,你是如何在网站上自动作品的理解指标。特别是

用一段时间停止脚本:Thread.sleep(200);

被认为是一个非常糟糕的做法。不管你做什么都不要混合隐式和显式等待,事情会开始出错,显式等待是recommended solution

如果(因为它似乎是你的情况)页面正在被AJAX操作修改,等待页面加载将不起作用。不要等待页面加载,而是等待您测试的条件变为真实。这样,你给AJAX操作时间执行,如果你有问题,当超时发生时你会得到一个错误。

StaleElementReferenceException是由DOM找到元素后刷新 造成的。请记住,WebElement是页面上特定元素的参考 ,如果DOM get的refresed此参考被破坏,并且您需要再次找到元素以便能够与 进行交互。