(StaleElementException:Selenium) How do I handle this?

前端 未结 2 2096
小蘑菇
小蘑菇 2021-01-26 10:28

This is my first time first day working on selenium and I have no hands on experience on Web Technologies in depth either.

Working around, I have been facing StaleElemen

2条回答
  •  情深已故
    2021-01-26 11:03

    I can give you the idea to overcome staleness.

    Generally we will be getting the Stale Exception if the element attributes or something is changed after initiating the webelement. For example, in some cases if user tries to click on the same element on the same page but after page refresh, gets staleelement exception.

    To overcome this, we can create the fresh webelement in case if the page is changed or refreshed. Below code can give you some idea.

    Example:

    webElement element = driver.findElement(by.xpath("//*[@id='StackOverflow']"));
    element.click();
    //page is refreshed
    element.click();//This will obviously throw stale exception
    

    To overcome this, we can store the xpath in some string and use it create a fresh webelement as we go.

    String xpath = "//*[@id='StackOverflow']";
    driver.findElement(by.xpath(xpath)).click();
    //page has been refreshed. Now create a new element and work on it
    driver.findElement(by.xpath(xpath)).click();   //This works
    

    Another example:

    for(int i = 0; i<5; i++)
    {
      String value = driver.findElement(by.xpath("//.....["+i+"]")).getText);
      System.out.println(value);
    }
    

    Hope this helps you. Thanks

提交回复
热议问题