java - Java-selenium 上的 StaleElementReferenceException 错误

标签 java selenium webdriver

当我运行从 Flipkart.com 选择“立即购买”的代码时,出现 StaleElementReferenceException。这是我所拥有的,但它对我不起作用。

public void SelectItemfromPage(){

    WebDriver wd = new FirefoxDriver();

    wd.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    wd.get("http://www.flipkart.com");
    WebElement element = wd.findElement(By.xpath(".//*[@id='fk-top-search-box']"));
    element.sendKeys("moto g");
    element.submit();


    element.findElement(By.xpath(".//*[@id='products']/div/div[1]/div[1]/div/div[1]/a[1]/img")).click();
    element.findElement(By.xpath(".//*[@id='fk-mainbody-id']/div/div[7]/div/div[3]/div/div/div[6]/div/div[3]/div[1]/div/div[2]/div/div[2]/form/input[9]")).click();
}

最佳答案

你的做法是完全错误的。 您正在保存 WebElement 并重用它,这不是正确的方法。 当您将 WebElement 保存在对象(本例中为元素)中时,每当 DOM 发生更改时,WebElement 就会变得过时。 您需要执行以下操作:

WebDriver wd = new FirefoxDriver();

wd.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
wd.get("http://www.flipkart.com");
WebElement element = wd.findElement(By.xpath(".//*[@id='fk-top-search-box']"));
element.sendKeys("moto g");
element.submit();


wd.findElement(By.xpath(".//*[@id='products']/div/div[1]/div[1]/div/div[1]/a[1]/img")).click();
wd.findElement(By.xpath(".//*[@id='fk-mainbody-id']/div/div[7]/div/div[3]/div/div/div[6]/div/div[3]/div[1]/div/div[2]/div/div[2]/form/input[9]")).click();

关于java - Java-selenium 上的 StaleElementReferenceException 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32226201/

相关文章:

JAVA如何获取SWT或JFace内部图像

java - JAVA中的多线程

python - Selenium 无法在 CentOS 中启动 Chromedriver

java - Selenium Chrome 驱动程序的限制 Web 大规模抓取

python - Phantom JS 驱动程序有时无法定位元素

windows - Jenkins : Selenium GUI tests are not visible on Windows

java - web.xml : cvc-complex-type. 2.4.a 中出现错误:发现以元素 'context-root' 开头的无效内容

java - Selenium Java 中的西里尔字母标题

c# - 如何使用Selenium元素等待、检查、点击而不会再次找到元素?

javascript - 如何使用selenium Webdriver获取gmail的密码输入字段ID?