0

I'm new to selenium webdriver, and I am working on testing a form using java and I encounter an issue of not being able to reuse instances of WebElement

WebElement element = driver.findElement(By.name("number"));
element.sendKeys("4");

// submit form this clears the element text box

element.sendKeys("7");  // this won't type 7 in the box?

But this works:

WebElement element = driver.findElement(By.name("number"));
element.sendKeys("4");

// submit form this clears the element text box

WebElement element2 = driver.findElement(By.name("number"));
element2.sendKeys("7"); 

Doesn't seem to make sense to have to instantiate another webelement object. Please give me insight, thanks.

3 Answers3

0

When you submit form which inturn clears the element text box essentially means the HTML DOM have refreshed and possibly either/all of the actions have happened :

  • Some new elements have been added to the DOM.
  • Some old elements are no more present in the DOM.
  • Some DOM element's attributes may have changed.
  • Inshort the HTML DOM have changed.

In this cases if you try to do :

WebElement element = driver.findElement(By.name("number"));
element.sendKeys("4");
// submit form this clears the element text box
element.sendKeys("7");

Selenium will complain about StaleElementReferenceException

Hence the solution is to search the desired element again afresh and then invoke the sendKeys() method as follows :

WebElement element = driver.findElement(By.name("number"));
element.sendKeys("4");
// submit form this clears the element text box
WebElement element2 = driver.findElement(By.name("number"));
element2.sendKeys("7");
undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
0

You can try Page Factory concept in Page Object Model. Refer: http://toolsqa.com/selenium-webdriver/page-object-pattern-model-page-factory/

0

try this code :

WebElement element = driver.findElement(By.name("number"));  
element.sendKeys("4");  

// submit form this clears the element text box  

driver.navigate().refresh();  
(new WebDriverWait(driver,10)).until(ExpectedConditions.elementToBeClickable(By.name("number")));

element.sendKeys("7");  
cruisepandey
  • 28,520
  • 6
  • 20
  • 38