问题描述
我目前正在通过 python 中的 selenium 自动执行 ui 测试,并且一些 webElements 会定期更改,这会导致 StaleElementReferenceExceptions。
对于这些麻烦的元素,我目前的解决方案是使用 try-except-blocks 和一个 for 循环来封装它们。
for _ in range(numberOfTries):
try:
webElement = get_theNeededWebelement()
doSomethingWithWebElement(webElement)
break
except StaleElementReferenceException:
pass
else:
raise Error(specificErrorText)
我希望能够将 numberOfTries 和 specificErrorText 与 try 语句中的块一起定义,并将可重用逻辑转移到一个类中。
像这样使用的东西:
with StalenessExpector(numberOfTries,specificErrorText):
webElement = get_theNeededWebelement()
doSomethingWithWebElement(webElement)
有没有办法做这样的事情? 也许使用递归或适当的“with”语句?
解决方法
我觉得你的想法很好。
但是我会给 numberOfTries
一个默认值,因为我猜你想在大多数情况下使用它具有相同的值,比如 10
而且我认为您必须在 StaleElementReferenceException
的情况下添加一些小的延迟,以使页面在再次池化元素之前稳定
except StaleElementReferenceException:
sleep(0.1)
pass