I am currently automating ui-tests via selenium in python and some webElements are changing periodically which leads to StaleElementReferenceExceptions.
My current solutions for such troublesome elements is, to use try-except-blocks with a for-loop encasing them.
for _ in range(numberOfTries):
try:
webElement = get_theNeededWebelement()
doSomethingWithWebElement(webElement)
break
except StaleElementReferenceException:
pass
else:
raise Error(specificErrorText)
I would like to be able to just define the numberOfTries and the specificErrorText together with the block within the try-statement and transfer the reusable logic into a class.
Something to use like this:
with StalenessExpector(numberOfTries, specificErrorText):
webElement = get_theNeededWebelement()
doSomethingWithWebElement(webElement)
Is there a way to do something like that?
Maybe with recursion or a proper "with"-statement?