Reputation: 687
I have a very simple script that find all HREF in a page and iterate and logs it:
Photo search scroll
Go To https://xxx
${elements}= Get WebElements xpath://a[contains(@href,'photo')]
FOR ${element} IN @{elements}
Log ${element.get_attribute('href')}
END
It works perfectly fine. As I need to open a new browser for each of HREF I added Selenium Browser command:
Photo search scroll
Go To https://xxx
${elements}= Get WebElements xpath://a[contains(@href,'photo')]
FOR ${element} IN @{elements}
Log ${element.get_attribute('href')}
Go To ${element.get_attribute('href')}
sleep 2s
Capture Page Screenshot
Go Back
END
I always get this error after first iteration:
Resolving variable '${element.get_attribute('href')}' failed: StaleElementReferenceException: Message: stale element reference: element is not attached to the page document
(Session info: chrome=86.0.4240.111)
I'm unable to figure out why this happen. Any help/comments is appreciated. Many Thanks
###UPDATE I've created a list varible and addedd additional loop:
@{hrefs} = Create List
FOR ${element} IN @{elements}
Log ${element.get_attribute('href')}
Append To List ${hrefs} ${element.get_attribute('href')}
END
FOR ${href} IN @{hrefs}
Go To ${href}
sleep 2s
Capture Page Screenshot
END
now I obtain this error code:
Opening url 'Create List'
20:08:36.739 FAIL InvalidArgumentException: Message: invalid argument
(Session info: chrome=86.0.4240.111)
Upvotes: 3
Views: 106
Reputation: 20067
why this happens
Because when you called Get WebElements
you got references to objects in the current page & session; the browser also keeps the same references, to the current DOM elements.
When you go to a different page and then back, this is a different page for the browser. Visually it is the same; its html is the same.
But for the browser, this is a different page than the one you started from; its internal references to the elements in it are different (the "map" it builds for the page you're browsing). In the same time, you request from the browser to give you an object by a reference. But the browser doesn't have it - those objects are not called the same for it, the references are different. You've got a stale (expired, not valid, old) reference, not pointing to any DOM object it has in its "map". StaleElementReferenceException
:)
The solution - open the target links in a new tab; thus your page will not refresh, and the references will be valid. Or better, get all links, and open them in a new loop.
Upvotes: 3