Encountering a Selenium StaleElementException when attempting to resubmit a form after filling it

I am currently working on automating the filling of a form in one of my Selenium scripts. The form consists of 4 text fields with the following HTML structure:

<input class="class" id="id" name="name" value="" autocomplete="off" wtx-context="stuff" type="text">

Once the form fields are filled out, there is a submit button as shown in the HTML code below:

<input id="id2" class="class2" value="Add Material" wtx-context="morestuff" type="submit">

Although I have successfully automated the filling and submitting of the form using Java code, I encounter a StaleElement exception after submission. To work around this issue, I navigate back to the homepage and then return to the form page. However, I am looking for a more elegant solution. Below is the Java code I am currently using:

Page.WriteToField(Page.Input_number(), "111111111");
Page.WriteToField(Page.Input_number2(), "222222222");
Page.WriteToField(Page.Input_date(), format.format(cal.getTime()));
Page.WriteToField(Page.Input_number3(), "3333");
Page.SubmitIngredient();

The WriteToField() function is defined as follows:

public void WriteToField(WebElement field, String text) {
    field.click();
    field.clear();
    field.sendKeys(text);
}

To access all the WebElements in my page classes, I use the following format:

public WebElement Input_number() {
    return wait.until(ExpectedConditions.elementToBeClickable(By.id("form1")));
}

Answer №1

Have you considered verifying the presence of an element before determining if it is clickable?

public WebElement Input_number() {
      wait.until(ExpectedConditions.presenceOfElementLocated(By.id("form1")));
      return wait.until(ExpectedConditions.elementToBeClickable(By.id("form1")));
}

Update- I suggest adding an Expected condition for the presence of an element because it performs a find element operation again. [See the implementation of the presenceOfElementLocated method below] This way, one would likely get the element in return. [Although, I could be mistaken]

public static ExpectedCondition<WebElement> presenceOfElementLocated(final By locator) {
    return new ExpectedCondition<WebElement>() {
        public WebElement apply(WebDriver driver) {
            return ExpectedConditions.findElement(locator, driver);
        }

        public String toString() {
            return "presence of element located by: " + locator;
        }
    };
}

In addition, if you review the implementation of the elementToBeClickable method [see code block below], it does not perform a find operation. If the element is not visible or enabled, it throws a StaleElementReferenceException exception.

 public static ExpectedCondition<WebElement> elementToBeClickable(final WebElement element) {
    return new ExpectedCondition<WebElement>() {
        public WebElement apply(WebDriver driver) {
            WebElement visibleElement = (WebElement)ExpectedConditions.visibilityOf(element).apply(driver);

            try {
                return visibleElement != null && visibleElement.isEnabled()?visibleElement:null;
            } catch (StaleElementReferenceException var4) {
                return null;
            }
        }

        public String toString() {
            return "element to be clickable: " + element;
        }
    };
}

Considering the element's presence before its visibility makes logical sense to me. [As mentioned previously, I could be mistaken]

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am curious as to how this function is aware of the specific attribute that is being passed

I've been experimenting with a little application that fetches a list of movies from an API. You input a word and it returns all movies with that word in the title. Here's the code responsible for fetching the list: var getMovies = function (que ...

ElementNotFoundException: Error: element not found: Element with the specified CSS selector ".selected" could not be located

Click here for image description. This is my initial experience with utilizing selenium, and I would greatly appreciate any assistance in resolving this issue. "NoSuchElementException: Message: no such element: Unable to locate element: {"method ...

JavaScript code for iframe auto resizing is not functioning properly on Firefox browser

I have implemented a script to automatically resize the height and width of an iframe based on its content. <script language="JavaScript"> function autoResize(id){ var newheight; var newwidth; if(document.getElementById){ newh ...

What is the best way to integrate Socket.IO into an Electron application?

I've been looking to incorporate Socket.IO into my Electron application, but the lack of documentation and examples has made it quite challenging. I would greatly appreciate if someone could provide insights on how multiple clients can communicate thr ...

Mysterious attributes - utilizing react and material-ui

In my current project, I am using react and material-ui. This is the code snippet from one of my components: <Dialog title="Dialog With Actions" actions={actions} modal={false} open={this.state.open} onRequestClose={this.handleClose ...

Understanding the moment when the DOM is fully rendered within a controller

I'm currently facing an issue with AngularJS. In my controller, I have a $watch setup like this: function MyController() { $watch('myModel', function() { $rootScope.$emit('do-oper'); }); } The value of 'myMod ...

Using AngularJS translation capabilities with UI Router

I am working on an AngularJS application that utilizes the AngularJS Translate library from . The setup includes UI router to maintain the existing URL structure of the website, which has been indexed by Google with various language versions such as www.do ...

Can you provide guidance on achieving a gradient effect throughout the mesh, similar to the one shown in the example?

Check out my code snippet on JSFiddle: https://jsfiddle.net/gentleman_goat66/o5wn3bpf/215/ https://i.sstatic.net/r8Vxh.png I'm trying to achieve the appearance of the red/green box with the border style of the purple box. The purple box was created ...

Is it possible for Robot Framework to facilitate keyword-driven testing for a GUI developed in C#?

Just dipping my toes into the world of automated testing! I'm wondering how to create keyword-driven tests with the robot framework for a GUI developed with .NET. Feeling a bit unsure about this process. ...

Issue with AJAX - button click event triggers on the second click

On my aspx page, I have implemented an UpdatePanel control to enable users to post comments and delete them later. However, I am encountering a peculiar issue where the first attempt at deleting a comment is successful, but subsequent deletions require two ...

Ways to automatically update React.js state when localStorage changes occur

Is it possible to automatically update the data on the cart page whenever there are changes made to the myCart array in localStorage? Below is the code that I am currently using: const [cart, setCart] = React.useState([]) React.useEffect(() => { se ...

Guide on stopping a webpage from loading and extracting text from it

I am trying to extract text from a URL shortener using the following code: import os from selenium import webdriver from selenium.webdriver.common.by import By os.environ['PATH'] += 'C:/Selenium Drivers' driver ...

Java WebDriverException caused by org.openqa.selenium

As a manual tester transitioning into Automation, I am currently learning how to use Selenium Webdrivers with Java to open a Chrome browser. However, I keep encountering an exception that states the Chrome binary cannot be found. Despite trying various s ...

Vue component architecture

Just started exploring Vue last night, so the answer might be obvious. I came across components with this layout: <template> <Slider v-model="value"/> </template> <script> import Slider from '@vueform/slider' ...

How to stop the HTTP Basic Auth popup with AngularJS Interceptors

In the process of developing a web app using AngularJS (1.2.16) with a RESTful API, I encountered an issue where I wanted to send 401 Unauthorized responses for requests with invalid or missing authentication information. Despite having an HTTP interceptor ...

Are Angular HTTP observables distinct in their behavior in comparison to standard observables?

While experimenting with Angular routing, I decided to utilize an in-memory database to retrieve information about the heroes. The original StackBlitz project can be found here. If you go to the heroes tab, select a hero, and modify their name, you' ...

Having issues with uploading a webcam picture using ajax. Occasionally the image only seems to be saved partially. Any suggestions on what I might be

Working on my web application involves taking customer photos and uploading them with Ajax. I base64 encode the pictures, resulting in large data sizes (around 1.4MB). The process involves Ajax calling a php script to handle the data transfer and saving it ...

Text that is selected within a contenteditable div: Find the beginning and end points of the highlighted text

<div contenteditable="true">This text is <b>Bold</b> not <i>Italic</i> right?</div> For instance, if the text appears in a bold format, but not italic and the user selects it, how can I determine the exact position ...

Guide to utilizing JSON strings in JavaScript

I am facing an issue with a function var url = "MyAvailability.aspx?mode=get"; $.get(url, function(data) { alert(data); }); This function returns a Json string representation of events: events: [{'id': 1,& ...

The functionality of Angular 5 reactive form valueChanges is not functioning correctly

I am currently working with a form inside a service: this.settingsForm = this.formBuilder.group({ names: this.formBuilder.array([]), globalIDs: this.formBuilder.array([]), topics: this.formBuilder.array([]), emails: thi ...