2017-02-01 46 views
-1

當我使用列出的方法來查看某個元素是否在頁面上可見時,我收到一個異常,指出它的無法使用指定的定位器查找元素。硒方法visibilityOf - 似乎沒有工作?

任何想法,有沒有人遇到過這個問題,甚至有更好的方法?

public boolean isElementPresentByWebElement(WebElement element) { 
    Wait<WebDriver> fluentWait = new FluentWait<WebDriver>(driver).withTimeout(15, TimeUnit.SECONDS) 
      .pollingEvery(1, TimeUnit.SECONDS).ignoring(NoSuchElementException.class); 

    for (int i = 0; i < 2; i++) { 
     try { 
      fluentWait.until(ExpectedConditions.visibilityOf(element)); 
      System.out.println("Element is visible: " + element.toString()); 
      return true; 
     } catch (Exception e) { 
      System.out.println(
        "Unable to locate the element: " + element.toString() + ", Exception: " + e.toString()); 
      throw (e); 
     } 
    } 
    return false; 
} 

enter image description here

+0

@anderson請找HTML代碼attatched – Gbru

+0

@Andersson請找HTML代碼attatched – Gbru

+0

可以讓我知道你有哪些進口例外。它應該是org.openqa.selenium.NoSuchElementException; –

回答

1

我覺得你的代碼是什麼你正在嘗試做的過於複雜。有一個內置的課程,ExpectedConditions,將做你想做的。你也在循環不必要的等待。我建議你通過定位器(By)而不是WebElement。它會擴展你使用這個功能的能力,因爲你在使用這個功能之前不需要找到這個元素。

public boolean isElementPresentByLocator(By locator) 
{ 
    try 
    { 
     new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOfElementLocated(locator)); 
     System.out.println("Element is visible: " + locator.toString()); 
     return true; 
    } 
    catch (TimeoutException e) 
    { 
     System.out.println("Unable to locate the element: " + locator.toString() + ", Exception: " + e.toString()); 
     return false; 
    } 
} 

下面的代碼更多地是直接翻譯和簡化您的代碼。

public boolean isElementPresentByWebElement(WebElement element) 
{ 
    try 
    { 
     new WebDriverWait(driver, 15).until(ExpectedConditions.visibilityOf(element)); 
     System.out.println("Element is visible: " + element.toString()); 
     return true; 
    } 
    catch (TimeoutException e) 
    { 
     System.out.println("Unable to locate the element: " + element.toString() + ", Exception: " + e.toString()); 
     return false; 
    } 
} 
-1

更新時間:

嘗試使用以下:

int waitCounter = 0; 

public static void WaitUntilVisible(WebDriver driver, WebElement element) throws InterruptedException, IOException { 
try { 


    WebDriverWait wait = new WebDriverWait(driver, 20); 


    wait.until(ExpectedConditions.visibilityOf(elementToBeClicked)); 
    if (!elementToBeClicked.isDisplayed()) { 

     System.out.println("Element not visible yet. waiting some more for " + element); 
     if (waitCounter < 3) { 
      waitCounter++; 
      WaitUntilVisible(element); 
     } 
     waitCounter = 0; 
    } 

} catch (Exception e) 

{ 
    System.out.println("Handling exception"); 
} 
} 
+0

這段代碼不會編譯。您正在使用幾個未聲明的變量,並且已經引入了未定義的'Logger_Info()'。 – JeffC

+0

你只需要初始化'waitcounter = 0'而不是'logger_info'使用'System.our.println' – kushal