How to avoid “StaleElementReferenceException” in Selenium?

前端 未结 16 2373
一向
一向 2020-11-22 12:12

I\'m implementing a lot of Selenium tests using Java. Sometimes, my tests fail due to a StaleElementReferenceException. Could you suggest some approaches to mak

16条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-22 12:35

    There could be a potential problem that leads to the StaleElementReferenceException that no one mentioned so far (in regard to actions).

    I explain it in Javascript, but it's the same in Java.

    This won't work:

    let actions = driver.actions({ bridge: true })
    let a = await driver.findElement(By.css('#a'))
    await actions.click(a).perform() // this leads to a DOM change, #b will be removed and added again to the DOM.
    let b = await driver.findElement(By.css('#b'))
    await actions.click(b).perform()
    

    But instantiating the actions again will solve it:

    let actions = driver.actions({ bridge: true })
    let a = await driver.findElement(By.css('#a'))
    await actions.click(a).perform()  // this leads to a DOM change, #b will be removed and added again to the DOM.
    actions = driver.actions({ bridge: true }) // new
    let b = await driver.findElement(By.css('#b'))
    await actions.click(b).perform()
    

提交回复
热议问题