Python Selenium WebDriverWait and click Directly specifying StaleElementReferenceException ()
Ok, here goes my attempt at explaining this problem that I haven't figured out for myself yet. I am using Selenium with python bindings and seems to have a problem with randomly not found page element when used WebDriverWait
followed by an event click()
. Here is my code:
yearOption = WebDriverWait(self.br, 40).until(lambda d: d.find_element_by_xpath("//select[@name='ctl00$holdSection$rptCommissionYears']/option[@value='%s']" % year), self.br)
print yearOption.text
yearOption.click()
This set of commands is in a for loop and is randomly interrupted in an event .click()
, creating an error: StaleElementReferenceException()
after printing yearOption.text
. This is completely strange to me, as the line WebDriverWait
obviously found the element and I didn't reload or change the browser state before clicking the element ...
Any ideas why I am getting this error? Remember this doesn't happen sequentially, infact - sometimes my entire script will execute successfully without errors.
source to share
I've faced similar issue before and I'm 99% sure your problem is the same.
If you check your loop:
- Look for this item
- Click
- Look for the same item
- Click on the link
Normal after click, some page reloads or changes occur. This may affect the item you are looking for. And if you don't care, you can end up looking for an element before reloading, and when you click on it, the element's id has already changed, so you'll get a Stale exception.
Lets go one by one:
- The page is loading and you have ID = 1
- You will find it.
- You will click on it and reload / change start.
- You enter another loop and find an item. Note that this can even happen very quickly as there is no wait after being clicked, and therefore find can exit by getting the ID = 1 element again. You are trying to click the item ID = 1, but since it has been reloaded it no longer exists.
You can fix this in different ways:
- If speed is not an issue, you can add an explicit wait after click for a few seconds, giving enough time for the javascript to complete.
- You can store the id of the item and every time you look for it you check what is different and if not you wait and try again.
By providing this, if it's not your problem, you can always share your code and target and I'll be happy to help.
source to share