1

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?

Prophet
  • 32,350
  • 22
  • 54
  • 79
Bavid
  • 17
  • 4
  • Please do not edit questions with solutions. This is what answers are for. If you found a solution in another question then please flag this one as a duplicate – Dharman Nov 15 '21 at 13:31

1 Answers1

-1

I found an answer elsewhere:

It seems that it isn't possible to access the code within the with statement. The thing I wanted to achieve is possible via passing a codeblock to a function as described here

Bavid
  • 17
  • 4
  • 2
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 17 '21 at 08:04