Tips for troubleshooting the StaleElementReferenceError in selenium automation

Encountering the persistent issue of receiving the error message

StaleElementReferenceError: stale element reference: element is not attached to the page document
every time I attempt to extract the text from a page body using Selenium. Numerous attempts have been made to resolve this, but unfortunately without success.

Code snippet:

function eduMobile(driver)
{
  driver.get(process.env.URL)
  
  // PIN login
  const pinEntry = driver.findElement(By.xpath('//*[@id="inputPin"]'))
  pinEntry.sendKeys(process.env.PIN)

  const pinOkBtn = driver.findElement(By.xpath('/html/body/div/form/input[2]'))
  pinOkBtn.click()

  // get body
  var mobile_body = driver.findElement(By.xpath("/html/body"))
  mobile_body.getText().then(function (text) {
    console.log(text);
  });

}

An attempt was made to rectify the issue with the following code snippet, which also yielded no success:

mobile_body.getText().then(function (text) {
    console.log(text);
  });

Initialization of my driver:

  let driver = new webdriver.Builder()
    .forBrowser(Browser.CHROME)
    .setChromeOptions(new chrome.Options().headless())
    .build()

Complete error message received:

C:\Users\andri\node_modules\selenium-webdriver\lib\error.js:522
    let err = new ctor(data.message)
              ^

StaleElementReferenceError: stale element reference: element is not attached to the page document
  (Session info: headless chrome=102.0.5005.115)
    at Object.throwDecodedError (C:\Users\andri\node_modules\selenium-webdriver\lib\error.js:522:15)
    at parseHttpResponse (C:\Users\andri\node_modules\selenium-webdriver\lib\http.js:549:13)
    at Executor.execute (C:\Users\andri\node_modules\selenium-webdriver\lib\http.js:475:28)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)
    at async thenableWebDriverProxy.execute (C:\Users\andri\node_modules\selenium-webdriver\lib\webdriver.js:735:17) {
  remoteStacktrace: 'Backtrace:\n' +
    '\tOrdinal0 [0x0064D953+2414931]\n' +
    ...additional stack trace lines...
    '\tRtlGetFullPathName_UEx [0x777E8FBD+1165]\n'
}

Your help in resolving this matter would be greatly appreciated!

Answer №1

It appears that the code snippet mentioned above is causing a redirect or page re-render to occur.

const pinOkBtn = driver.findElement(By.xpath('/html/body/div/form/input[2]'))
pinOkBtn.click()

StaleElementReferenceError occurs when a WebElement is assigned to a variable, and then that WebElement (or the entire page) is re-rendered, making it difficult for the driver to locate the specific DOM element again.

In this scenario, it seems like the button is clicked, and immediately after querying the DOM and assigning the body to a variable, the page gets re-rendered.

To troubleshoot, try setting a breakpoint at

var mobile_body = driver.findElement(By.xpath("/html/body"))

Wait until the page has completely loaded before resuming debugging. If this resolves the issue, you can implement a wait mechanism to ensure the page is fully loaded. In Java, it could be implemented as:

    final String mySelector = "Some css selector (or xpath, or id) of an element on the page which would indicate that the page has been fully loaded";
    FluentWait<WebDriver> wait = new FluentWait<>(getDriver())
            .withTimeout(Duration.ofSeconds(10))
            .pollingEvery(Duration.ofSeconds(1))
            .ignoring(NullPointerException.class)
            .ignoring(StaleElementReferenceException.class);
    wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector(mySelector)));

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

Error: Sorry, there was an issue with the code (React)

I'm attempting to build a React project without Node, and I'm trying to call a JS file from an HTML file. This is just a simple example for learning purposes. However, I keep encountering the Uncaught SyntaxError: Unexpected token '<&apos ...

Node.js not receiving expected Ajax response

Why is my Ajax request not receiving the proper response? It always shows readyState '4' with a response status of '0'. What could be causing this issue? Client-Side Code: var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = f ...

How is it that the identical group is unable to produce an accurate line chart and its corresponding range chart?

Check out my code snippet on JSFiddle here: https://jsfiddle.net/8yf7j3k6/11/ I am currently working on replicating a similar visualization of my data for a range chart, allowing me to scrub through the chart while utilizing tooltips in the line chart rep ...

Setting up Authorization for FETCH requests in NEXT.js using .env.local

`export default function reservations() { let [reservationStock, setReservationStock] = useState([]); useEffect(() => { fetch(url, { headers: new Headers({ Authorization: "MyBasic Credentials", " ...

Tips on inserting text into form input fields

I need some guidance on how to enhance my form input functionality. The form currently consists of an input box and a submit button. When the user clicks submit, the form content is submitted and processed using javascript. What I am aiming for is to autom ...

Looking for non-case-sensitive letters in a text input field

Having trouble with case-insensitive search using jquery? The search option seems to be working fine, but there's an issue with uppercase and lowercase letters in the content. Check out my full code on jsfiddle where if I search for "senthil" it doesn ...

PDFMAKE: A Guide to Duplicating Elements in the 'Content' Array

I have an Array within Items. My goal is to display them in a Table format using PDFMake. table: { multiple pages headerRows: 2, widths: ['auto', 100, 200, 'auto', 'auto', 'auto'], body: [ ...

Is tsconfig.json Utilized by Gatsby When Using Typescript?

Many blog posts and the example on Gatsby JS's website demonstrate the use of a tsconfig.json file alongside the gatsby-plugin-typescript for TypeScript support in Gatsby. However, it seems like the tsconfig.json file is not actually utilized for conf ...

Using VBA and Selenium to automate image uploading on a designated website

Looking to upload an image on a specific website, so I need the necessary code for this task Sub UploadImage() Dim bot As WebDriver Set bot = New WebDriver bot.Start "chrome" bot.Get "https://www.qrcode-mo ...

Click the button to automatically generate a serial number on the form

My form includes three input fields: sl no, stationerytype, and stationeryqty. By clicking the symbols + and -, I can add or delete these fields. I am attempting to automatically generate a Sl no in the sl no field when I click the plus symbol, and adjust ...

Encountering a "Start script missing" error while trying to execute npm start, the problem remains even after attempting

Help, I keep encountering this issue npm ERR! missing script: start whenever I attempt to execute 'npm start' for my latest React project. I've tried searching for a solution and came across some individuals who were able to resolve it by u ...

Ordering dates by week in AngularJS 1

Currently, I have a list of objects: [{ name: one, date: 2017-09-18 }, { name: two, date: 2017-09-11 }, { name: three, date: 2017-09-13 }] I am looking to organize this list by week. Perhaps like the following structure: { 1week(or , m ...

Leveraging underscore.js for null verification

let name = "someName"; if(name !== null) { // perform some action } Currently, I am utilizing http://underscorejs.org/#isNull. How can I achieve the same functionality using underscore.js? Is there any noticeable performance enhance ...

React-bootstrap-table Axios delete operation causing [object%20Object] to be displayed in the browser console

I am having trouble executing a delete operation using axios on a react-bootstrap-table, and encountering this error in the console DELETE http://localhost:9000/api/terminals/[object%20Object] Uncaught (in promise) Error: Request failed with status cod ...

Streamline email error management within nested middleware functions

I have implemented an express route to handle password resets, which includes finding the user and performing some error handling. However, I am now faced with the challenge of adding additional error handling within a nested function, and I am uncertain a ...

Unable to input information into Textbox in real-time

Having trouble entering data from one page to another using ng-model. After filling in some information in a textbox and moving to the next page, I want the same data to be entered when I return to the previous page. I've written the code but it doesn ...

Retrieve data from multiple JSON tables using a JavaScript loop

Check out this Codepen for a working example. I am relatively new to Javascript, so I may not be approaching this problem the best way. If you have any suggestions on how I could improve my approach, I would greatly appreciate it; always looking to learn ...

Receiving an error message and identifying the specific line number within the catch

try{ cause error } catch(err){ console.log(err.lineNumber) //or console.log(err.line) } The error object has various properties like err.name, err.stack, and err.message, but I have been unable to find a way to log the line number of the error ...

What is the best way to dynamically change the content of a div based on user selection?

When a user selects an option in the HTML, I want to display another div set to Block. I tried putting the OpenAskuser() function in a button, but it didn't work either. It would be ideal if we could achieve this without a button. Just have the displ ...

jqGrid - Error when the length of colNames and colModel do not match!

Whenever I implement the code below, it triggers an error saying "Length of colNames and <> colModel!" However, if isUserGlobal is false, no errors occur. The version of jqGrid being used is 4.5.4 receivedColModel.push({name:'NAME', index: ...