Java Error and Selenium Stale Element

I continue to encounter a Stale Element bug in Selenium. From what I investigated, this error occurs when you navigate from a page or an element has been resized. I continue to encounter this error when I look through a list of web elements to try to determine one of them by value. It always fails in the if statement when I try to compare the name. Does anyone know what my problem is? On a larger question, is there a good fix for stale element error? All I saw on the Internet was to catch a mistake and skip it again. Is there a better way than this?

    int attempts = 0;
    while(attempts < 2){
    try{
    java.util.List<WebElement> elements = driver.findElements(By.tagName("span"));
    for(WebElement element: elements){
        if(element.getText().equals(elementName)){
          return element;
        }
    }
    }catch (org.openqa.selenium.StaleElementReferenceException e){
                e.printStackTrace();
    }
        attempts++;
    }
    return null;
+4
source share
1 answer

, . , , <span> -, foreach findElement , . getText. . , , - //span[text() == 'valueOfelementNameVariable'], WebDriverWait , .

, visibilityOfElementLocated, :

WebElement yourSpanElement = (new WebDriverWait(driver, 60))
  .until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//span[text() == \"valueOfelementNameVariable\"]")));

, WebDriverWait DOM , ExpectedCondition true -. :

public V (com.google.common.base.Function isTrue)

:

the function returns neither null nor false,
the function throws an unignored exception,
the timeout expires,
the current thread is interrupted

visibilityOfElementLocated

  /**
   * An expectation for checking that an element is present on the DOM of a page
   * and visible. Visibility means that the element is not only displayed but
   * also has a height and width that is greater than 0.
   *
   * @param locator used to find the element
   * @return the WebElement once it is located and visible
   */
  public static ExpectedCondition<WebElement> visibilityOfElementLocated(
      final By locator) {
    return new ExpectedCondition<WebElement>() {
      @Override
      public WebElement apply(WebDriver driver) {
        try {
          return elementIfVisible(findElement(locator, driver));
        } catch (StaleElementReferenceException e) {
          return null;
        }
      }

      @Override
      public String toString() {
        return "visibility of element located by " + locator;
      }
    };
  }

(, null, ), , -, .


?

Object Object. , PageFactory, , ( ), , WebElements , , , .

+2

Source: https://habr.com/ru/post/1530091/


All Articles