Stale element reference: element is not attached to the page document.


#1

Not a way to solve it, it happens intermittently, please help me.

04-03-2018 10:21:14 AM - [ERROR] - stale element reference: element is not attached to the page document

(Session info: chrome=65.0.3325.181)

(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)

Command duration or timeout: 0 milliseconds

For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html

Build info: version: ‘3.7.1’, revision: ‘8a0099a’, time: ‘2017-11-06T21:07:36.161Z’

System info: host: ‘NOT-104’, ip: ‘192.168.0.139’, os.name: ‘Windows 10’, os.arch: ‘amd64’, os.version: ‘10.0’, java.version: ‘1.8.0_102’

Driver info: com.kms.katalon.selenium.driver.CChromeDriver

Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.35.528161 (5b82f2d2aae0ca…, userDataDir: C:\Users\gcesario\AppData\L…}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 65.0.3325.181, webStorageEnabled: true}

Session ID: 5fb2aedc6fa347f6f399e459c1daf4dc

04-03-2018 10:21:14 AM - [ERROR] - Test Cases/Recebimento FAILED because (of) org.openqa.selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

(Session info: chrome=65.0.3325.181)

(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 10.0.16299 x86_64) (WARNING: The server did not provide any stacktrace information)

Command duration or timeout: 0 milliseconds

For documentation on this error, please visit: http://seleniumhq.org/exceptions/stale_element_reference.html

Build info: version: ‘3.7.1’, revision: ‘8a0099a’, time: ‘2017-11-06T21:07:36.161Z’

System info: host: ‘NOT-104’, ip: ‘192.168.0.139’, os.name: ‘Windows 10’, os.arch: ‘amd64’, os.version: ‘10.0’, java.version: ‘1.8.0_102’

Driver info: com.kms.katalon.selenium.driver.CChromeDriver

Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 2.35.528161 (5b82f2d2aae0ca…, userDataDir: C:\Users\gcesario\AppData\L…}, cssSelectorsEnabled: true, databaseEnabled: false, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: XP, platformName: XP, rotatable: false, setWindowRect: true, takesHeapSnapshot: true, takesScreenshot: true, unexpectedAlertBehaviour: , unhandledPromptBehavior: , version: 65.0.3325.181, webStorageEnabled: true}

Session ID: 5fb2aedc6fa347f6f399e459c1daf4dc


#2

Hi Gabriel

It would be nice to see the lines of code that caused the error.

If you believe that the object should be ready to interact with and sometimes this same test passes, then it is likely one of two things:

1 - The network/server is running slower than usual.

Perhaps you didn’t refresh the object being tested after the page
updated (possibly via ajax?) or you didn’t wait long enough for it to be
loaded/visible or otherwise addressable.

2 - WebDriver is lying to you.

This is a rare occurrence but happens often enough to cause you pain. There is a bug (certainly in the gecko driver) that causes that message to appear when it should not. The cause is a mystery. The cure is to avoid using WebUI.waitFor* and WebUI.click etc and write your own using JavaScript which allows you to deal more directly with the page. (Warning: This is not a trivial undertaking!)

Russ


#3

Russ, this is a line of code:
CustomKeywords.‘newpackage.newkeyword.clickUsingJS’(findTestObject(‘Page_GTI PLUG/span_Adicionar Produto’), 30)

I am using a JS command in Keyword to replace the click, but it does not always work, it follows below:

public class newkeyword {

@Keyword

def clickUsingJS(TestObject to, int timeout)

{

WebDriver driver = DriverFactory.getWebDriver()

WebElement element = WebUiCommonHelper.findWebElement(to, timeout)

JavascriptExecutor executor = ((driver) as JavascriptExecutor)

executor.executeScript(‘arguments[0].click()’, element)

}

}


#4

Are you waiting until that TO is visible before you call clickUsingJS?


#5

Yes, other buttons work with JS.


#6

Okay, let’s try this…

Firstly, does your element have an ID? It will just make this easier, if it does.

If not, just replace my-button with your ID:

def clickUsingJS2(String selector) {
  WebUI.executeJavaScript('document.querySelector("' + selector + '").click()', null)
}

And call it like so:

clickUsingJS2("#my-button")

if you have jQuery on the page (and you KNOW it’s “ready” to work with) you can do this:

def clickUsingJQ(String selector) {
  WebUI.executeJavaScript('$("' + selector + '").click()', null)
}

And call it just like before.


#7

Sorry Russ, I’m just inexperienced in all of this.
Where can I put this code?
Is not it the same as I do not put any place on my button?
Thank you!


#8

Put it right next to your Keyword code. Or, you can create another Keyword file/package if you wish, but the same file would make sense, I guess.

If you make those two methods static (I forgot to add that) then you don’t need to say @Keyword above them… unless you want them to appear in the Keyword dropdown in manual view (I never use that dropdown so I always remove @Keyword).

So make them look like this:

static void clickUsingJS2(String selector) {
  WebUI.executeJavaScript('document.querySelector("' + selector + '").click()', null)
}

If you need to return something from one of these methods, it’s probably best to “cast” the returned result accordingly. This example returns a String:

/**
  * Call somethingInteresting via javascript and querySelector.
  * @param selector (String) a CSS selector
  * @return String
 */
static String somethingUsingJS2(String selector) {
  return (String) WebUI.executeJavaScript('return document.querySelector("' + selector + '").doSomethingInteresting()', null)
}

Notice there are two return statements: one in Groovy code and one inside the javascript string. You can call it like this:

String x = somethingUsingJS2("#my-id")

Or…

WebUI.comment('Something interesting ' + somethingUsingJS2("#my-id"))

#9

Hi, I am trying to click on an element using LinkText.
Eg: myelement = driver.FindElement(By.LinkText(StoreFile)) 'Click on report by name

                logger.Debug("Report Found as " & myelement.Text)

                If myelement Is Nothing Then

                    GoTo endTry

                Else

                    myelement.Click()

                    logger.Debug("Report clicked is " & StoreFile)

                End If  

But, I get the following error:

The Error Is OpenQA.Selenium.StaleElementReferenceException: stale element reference: element is not attached to the page document

(Session info: chrome=66.0.3359.139)

(Driver info: chromedriver=2.35.528161 (5b82f2d2aae0ca24b877009200ced9065a772e73),platform=Windows NT 6.1.7601 SP1 x86_64)

at OpenQA.Selenium.Remote.RemoteWebDriver.UnpackAndThrowOnError(Response errorResponse)

at OpenQA.Selenium.Remote.RemoteWebDriver.Execute(String driverCommandToExecute, Dictionary`2 parameters)

at OpenQA.Selenium.Remote.RemoteWebElement.Click()

at ExcelAddIn1.Ribbon1.BrandReview(String ReadFile).

Is there a reason as to why it can’t find the element using the LinkText even though the element is visible on the web page? Is there a solution to resolve this, please?


#10

These articles describe this issue.

http://www.sahajamit.com/post/mystery-of-stale-element-reference-exception/

I have no solution for Katalon Studio yet.


#11

Has anyone found an answer for this that works? I’m trying the script as provided and not having any luck. We had to wrap SE code in C# here and used a try, catch combo. Is there anything like that to get past this. It’s making Katalon virtually unusable for me as it’s happening on pages that should take about 5 minutes to script. Thanks.


#12

I have uncovered two general principles when interacting with web pages through Katalon:

  1. Sometimes it is necessary to interact with elements through javascript
  2. Waiting won’t always resolve the issue. Retry clicking or inserting data even after waiting…

Case in point, I have pasted code below that will open www.katalon.com, log in, and perform a keyword search. After trial and error I found that by using a combination of javascript, and waiting and repeating steps as was able to accomplish this task:

//open browser

WebUI.openBrowser(“www.katalon.com”)

//click on login button to login

WebUI.click(findTestObject(‘Object Repository/Script/Page_Katalon Studio Best automated/a_Sign in’))

//enter username and password

WebUI.setText(findTestObject(‘Object Repository/Script/Page_Sign in Katalon Studio/input_user_email’), "xxxxx@xxxxx.com")

WebUI.setText(findTestObject(‘Object Repository/Script/Page_Sign in Katalon Studio/input_user_pass’), “xxxxxx” )

//click on sign in

WebUI.click(findTestObject(‘Object Repository/Script/Page_Sign in Katalon Studio/input_login-btn’))

//click on search

WebUI.click(findTestObject(‘Object Repository/Script/Page_Katalon Studio Free Download/img’))
//enter “script” in search field

WebUI.executeJavaScript(“document.getElementById(‘input_text_search’).value=‘script’;”, null)
//wait for search icon to become available and then click on search icon to perfom search

WebUI.waitForElementClickable(findTestObject(‘Object Repository/New Test Case/Page_Katalon Studio Free Download/img’), 50)

//repeat previous step but without waiting

WebUI.click(findTestObject(‘Object Repository/New Test Case/Page_Katalon Studio Free Download/img’))
//reenter “script” into search field

WebUI.executeJavaScript(“document.getElementById(‘input_text_search’).value=‘script’;”, null)
//reclick seach icon

WebUI.click(findTestObject(‘Object Repository/New Test Case/Page_Katalon Studio Free Download/img’))


#13

Julie Mortlock said:

Has anyone found an answer for this that works? I’m trying the script as provided and not having any luck. We had to wrap SE code in C# here and used a try, catch combo. Is there anything like that to get past this. It’s making Katalon virtually unusable for me as it’s happening on pages that should take about 5 minutes to script. Thanks.

I’m in the same boat here. Anyone have any updates on this?


#14

I am in the same boat. I can sometimes avoid the error by adding delays to the test steps but then it causes the test execution to take ridiculously long.