2013-01-08 96 views
0

是否可以在等待元素出現時執行命令?特別是我等待一個元素出現,但除非刷新頁面,否則不會出現。這裏是我的代碼Selenium - 如何在WebDriverWait wait.until運行時執行命令

wait = new WebDriverWait(driver, 30); 
element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath_here"))); 
state = element.getText(); 

我在等元素是永遠不會出現,除非我打了應用程序的刷新按鈕。在我設置的30秒超時期間,如何刷新?

+0

爲什麼你不會刷新然後等待元素?爲什麼在等待期間你必須刷新**? –

+0

嗯,我在等待之前做了一個刷新,但是元素可能不會在那裏,在這種情況下它會失敗,因爲不管我等多久,除非我再次刷新元素都不會出現。我想我可以把等待放在一個循環中,這樣我可以刷新並等待幾次。 –

+0

所以你必須刷新多次?你有刷新的限制嗎? (數量或時間) –

回答

0

我會在該代碼中添加更多行:基本上,如果state.isEmpty()然後使用Webdriver「Action」類將鼠標移動到刷新按鈕(您的應用程序需要一個刷新按鈕工作),然後再運行一次等待來驗證它是否出現。

1

你可以做這樣的事情:

System.out.println("before wait"); 
    WebElement el = (new WebDriverWait(driver, 30)) 
     .until(new ExpectedCondition<WebElement>(){ 
     //try the following cycle for 30 seconds 
     @Override 
     public WebElement apply(WebDriver driver) { 
      //refresh the page 
      driver.navigate().refresh(); 

      System.out.println("Refreshed"); 
      //look for element for 5 seconds 
      WebElement sameElement = null; 
      try{ 
       sameElement = (new WebDriverWait(driver, 5)) 
         .until(new ExpectedCondition<WebElement>(){ 
        @Override 
        public WebElement apply(WebDriver driver) { 
         System.out.println("Looking for the element"); 
         return driver.findElement(By.id("theElementYouAreLookingFor")); 
        }});  
      } catch (TimeoutException e){ 
       // if NULL is returns the cycle starts again 
       return sameElement; 
      } 
      return sameElement; 
    }});   
    System.out.println("Done"); 

它將嘗試獲取元素30秒,刷新頁面每隔5秒。