0

I am getting StaleElementReferenceException when I run my code for selecting "Buy NOW" from flipkart.com. This is what I have, but its not working for me.

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();
}
1
  • Homewrecker has the right answer. Also... doing element.findElement() only searches children of element, not the entire page... which is probably also not what you intended here. Commented Aug 26, 2015 at 16:49

1 Answer 1

2

Your approach is all wrong. You are saving an WebElement and reusing it, that's not the way to go. When you save a WebElement in an object, in this case element, the WebElement will become stale whenever the DOM changes. What you need to do is the following:

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.