Selenium: intermittent "element not found" issues - selenium

Every now and then my selenium tests randomly fail with an "element X not found" error message. I do a simple select by ID, eg.
click('sideBar_queryButton')
When I use the dom inspector, the element is there, so I wonder why selenium doesn't find it sometimes. When I run the same test again, it works or it breaks again, there seems to be no reliable way of reproducing it. Even tests which are there for ages seem to randomly break and then magically work again. Inserting a few sleep statements sometimes helps but not reliably. So I wonder if I'm using it incorrectly. Has anyone else had these problems with selenium and if so, how did you fix them?

Edit: I found it to be much more reliable to put some test markers in my pages and wait for them to appear. If you use asynchronous operations which might create race conditions in your tests, inserting a test marker into your html after you finish the operation worked pretty well for me. E.g.
$('<div>').addClass("testMarker").append("OpXYZFinished").appendTo($('#content'));
That way, you can do a simple "waitForTextPresent" to see if things worked out and its much more reliable than guessing the browser's loading state. The testmarker class needs to be formatted in a way that it is not visible to the user (e.g. font color == background color).
Thanks for all your comments. After some deeper digging on the net and
in our tests I finally found combining these statements instead of a
simple waitForPageToLoad to be the cure for our issues:
waitForPageToLoad('')
// wait until all ajax activity has ceased. That check's jQuery's $.active
waitForCondition('selenium.browserbot.getUserWindow().$.active == 0', 5000)
// wait a second for all JS to properly initialize
pause(1000)
There is still a pause in there which is somewhat ugly, but it does
the trick.

Related

EXCEPTION: stale element reference: element is not attached to the page document

My HTML-Page contains (among other stuff) this bit:
<ol id="links">
<li id="links_1">stackoverflow</li>
</ol>
In my code to test the page, I then do:
el←FindElementById'links_1'
(ACTIONS.MoveToElement el).Build.Perform
and this crashes with
EXCEPTION: stale element reference: element is not attached to the page document
(Session info: chrome=81.0.4044.129)
However, this error doesn't seem to be justified, as the element is still alive:
el.Displayed
1
el.Text
stackoverflow
el.Location
{X=56,Y=282}
How can I fix this problem?
(The environment is APL. I've left out a few APL-details here because I feared they might be avoidable "distraction" from the core-issue)
During my research before posting, I saw the question stale element reference: element is not attached to the page document but it doesn't seem to apply:
as shown, I'm doing the FindElementById and access it immediately after finding it. The DOM doesn't change, page is static.
explanations about it no longer being part of the DOM do not apply: it is found and, as I attempted to show, I can access properties such as Displayed or Text.
I also went through the reference, but this explanation did not help.
Also, there is no looping going on and nothing changes the page. It's really straightforward: GoToUrl * Find * MoveToElement.
I removed the chromedriver-tag, as I can repro this with Firefox and geckodriver. However, with geckodriver, I get "EXCEPTION: Web element reference not seen before:" when I do MoveToElement - but I can do el.Click and access its properties in exactly the same way that as with Chrome.
Update: a coworker investigated this a bit deeper (beyond my comfort zone) and found that before throwing this "stale exception", there is (I'm not sure how to word this properly and where exactly it occurred) a 404-exception. I just know 404 as an HTTP Status-code - that's all it means to me. But clearly the browser was not asked to navigate anywhere, so I can't be related to an HTTP404. Does that perhaps ring some bells with anyone more familiar with the internals of WebDriver?
This was a complex and multi-layered problem, but when I finally removed all layers - it worked!
The key-factor which caused this problem:
due to a fault in the way I had written the test caused it to be executed twice - and the 2nd run always exposed the problem.
I had instantiated ACTIONS in the test-framework and was not aware of a critical feature: it continuously builds a chain of actions, any Build.Perform..-steps just added to that. Solution: create separate instances of every run (possibly, since it's fairly lightweight) or call ACTIONS.Reset(requires WebDriver4). I've never had issues with WD4 (although it still is in alpha) - but this gave the ultimate reason to switch!

When invoking js.exec in Geb/Spock, the exec method is flagged as 'null'

I am creating a suite of tests (using Geb/Spock) for a web site. In one of them, the element I want to access is on the top of the page, so, to make sure that is visible, I want to scroll to the top of the page.
The command I am using is:
browser.js.exec('window.scrollTo(0, 0);')
or variations of it like
js.exec('window.scrollTo(0, 0);')
or other alternative like:
js.exec('window.scrollBy(0, -250);')
None of them makes the page scroll up, and when executing I get the following error (it is the only error, no other feedback). The error message using the other options listed above is identical (other than the command itself):
Condition not satisfied:
browser.js.exec('window.scrollTo(0, 0);')
| | |
| | null
| geb.js.JavascriptInterface#4019094f
geb.Browser#3dcac33e
at UserCreatesCompany.Go to Home Page and click on the log to
GitHub button as user User1(UserCreatesCompany.groovy:170)
I can not interpret the message that 'exec' is null. What exactly it means?
To make things more interesting, at the end of this script I am running the following cleanup procedure
js.exec('window.scrollTo(0, document.body.scrollHeight);')
DeleteButton.click()
$("button",'data-automation-id':"button-modal-yes").click()
}
and that works well: the page scrolls down. So, does not seem a problem about some missing library.
Any suggestion of what I may be doing wrong?
The version of the different components I am using is:
groovyVersion = '2.5.4'
gebVersion = '2.3'
seleniumVersion = '3.141.59'
chromeDriverVersion = '2.45'
First of all, you should not need to ever manually scroll the page to make elements visible - Selenium WebDriver which is underpinning Geb will do that for you automatically as soon as you start interacting (clicking, setting value, etc) with content.
Secondly, the failure you are getting is a failed assertion coming from a statement in an automatically asserted (then: or expect:) Spock block. It feels to me that you don't understand a concept which is core to Spock and therefore you should read about it in the manual first. It should make the failure you're getting clearer.
Thanks for the answer. Clearly: I was not fully aware of the different constrains the different blocks impose on what is executable or not. The manual is pretty clear once you have stumbled!
I am intrigued by your first assertion pointing that Selenium WebDriver will move to the element as soon as I interact with it. That was my understanding but it was not working. I made sure the element in question had a unique identifier, but still, it was not able to found it if the element had to be found by scrolling up. On the other hand it worked smoothly when locating the element WebDriver scrolled the page down.
Thanks again for the explanation. I have learn something new today!

Selenium Silly GetAttribute Issue. Debug vs running code java

I'm using Eclipse/Java and interfacing with the Selenium chrome webdriver.
The code I'm executing is
Sting sValue = item.getAttribute("innerHTML");
If I am stepping over this code it works fine.
Otherwise, if I just run the code. It throws a NUllPointerException.
What gives? Any ideas?
Thanks!
It's possible the page doesn't have enough time to load when you run straight through, but when you step with the debugger it's just enough extra time for the page to finish loading and avoid the NullPointerException. Try adding a wait, as described in the accepted answer for this question: Getting Selenium to pause for X seconds.
This is not a real answer, it's just a total hack! I have to get some things done so I'll investigate predicates and WebDriverWaits later.
I was creating a list of webelements:
List wElements = getElements()
Then I was trying to get the innerHTML from each webelement in the list.
It works fine in debug mode, but when I execute the code it fails to gather the information IN SOME OF THE ELEMENTS in the collection. So what I did was retrieve the same list a second time.
List wElementsB = getElements()
Then I retrieved the innerHTML out of the wELementsB. Works fine.
I tried sleeping and telling the webdriver to wait. but those failed as well.
Thanks Guys!

Instruments fails to execute send_keys intermittently. How should that be handled?

The Problem: I'm using Appium's python client to send_keys to a WebElement.
And Instruments decides it shouldn't tap certain keys sometimes.
This is a pain when I'm trying to do things like login. I need to be able to reliably type or programmatically set values on input fields.
This is (more or less) what I'm doing, and here's the gist of Instruments complaining about it:
el = driver.find_element_by_xpath('//UIATextField[1]')
el.click()
el.send_keys('ABCDEFGHI')
All pretty standard. And it usually works
But usually isn't cutting it. I need something solid.
Possible Solutions?
I think I can make send_keys work if I do some sort of try/retry if I get a WebDriverException back.
But what would be really cool is if I could set the value of the element through a JavaScript execute_script - or better yet - a selenium python binding!
I don't know JavaScript, and I've already tried searching for how to set the value on the object without doing sendKeys but I've come up blank.
Any ideas would be really helpful. Thanks!
Solution below:
# Get the element
el = driver.find_element_by_class_name('UIATextField')
driver.execute_script("au.getElement('%s').setValue('%s')" % (el.id, 'ABCDEF'))
# At this point, the keyboard is opened and the text is instantly entered.

selenium webdriver sendkeys issue on IE - frame moves/shifts

I am using webdriver with IE 9.
When I exceute a "sendkeys" on my webelement the content of the relevant frame moves/shifts upwards.
I debugged my code and the strange behaviour occurs exactly in that moment when this line is executed:
searchTerm.sendKeys(searchString);
"searchTerm" is a Webelement, which is created by the PageFactory in that class. In my case it is a "textbox".
Although it is possible to write text into my textbox, I am struggling with that strange behaviour and would like to get rid of this. The problem is that the affected frame move above other existing frame and elements...
I dont have this problem when using firefox...
Any Ideas?
Thanks in advance and best regards,
Thomas
If you're referencing to that it scrolls the content of a frame strangely, then that's something you'll have to live with. WebDriver had (and sometimes still has) serious trouble with interacting with elements when it had to scroll to them, that's why there's some aggressive scrolling involved. It should be harmless since it doesn't actually change anything.
If it really changes the page layout, then that's a problem which should be closely examined. File a bug at http://code.google.com/p/selenium/issues/entry or post some relevant testcase here.