2017-01-09 43 views
0

我需要等到javascript匹配字符串或布爾值的結果。Selenium - 等到返回的JavaScript腳本值匹配值

憑藉此javascript:

document.getElementById('video_html5').seeking; 

我得到一個「假」 /「真」值,我需要等到值是「假的」,所以我敢肯定,視頻是不是尋求,但我只找到了等待javascript命令值的方法,而不是檢查值是否與某些文本匹配的方式。

new WebDriverWait(driver, 30) 
    .until(ExpectedConditions.jsReturnsValue("return document.getElementById('video_html5').seeking;")); 

因爲在某些情況下,我得到一個非布爾值的字符串,並且需要比較這些字符串。

我發現如何做到這一點的Ruby,但沒有在Java中:

wait_element = @wait.until { @driver.execute_script("return document.getElementById('vid1_html5_api_Shaka_api').seeking;").eql? false } 
+0

這工作? 'jsReturnsValue(「document.getElementById('video_html5')。seeking ==='false'?'true':undefined;」)它會直接在JavaScript中比較值,如果seek爲true則返回undefined。 –

回答

2

您可以編寫自己的自定義預計的條件。

public class MyCustomConditions { 

    public static ExpectedCondition<Boolean> myCustomCondition() { 
    return new ExpectedCondition<Boolean>() { 
     @Override 
     public Boolean apply(WebDriver driver) { 
     return (Boolean) ((JavascriptExecutor) driver) 
      .executeScript("return document.getElementById('video_html5').seeking === 'string_value' || ... "); 
     } 
    }; 
    } 
} 

然後在您的測試中,您可以使用如下條件。

WebDriverWait wait = new WebDriverWait(driver, 30); 
wait.until(MyCustomConditions.myCustomCondition()); 
+0

事情是,我更喜歡某種通用的方式來做到這一點,因爲我需要使用javascript結果對字符串進行多次比較,所以如果可能的話,我寧願不必爲每個比較都添加一個customCondition。 –

+0

也許你可以創建一個具有通用邏輯的條件,然後根據需要傳遞特定的參數。 – cjungel

1

一個通用的方法來做到這一點(其中command是JavaScript要與webdrivertimeout秒運行):

public Object executeScriptAndWaitOutput(WebDriver driver, long timeout, final String command) { 
    WebDriverWait wait = new WebDriverWait(driver, timeout); 
    wait.withMessage("Timeout executing script: " + command); 

    final Object[] out = new Object[1]; 
    wait.until(new ExpectedCondition<Boolean>() { 
    @Override 
    public Boolean apply(WebDriver d) { 
     try { 
     out[0] = executeScript(command); 
     } catch (WebDriverException we) { 
     log.warn("Exception executing script", we); 
     out[0] = null; 
     } 
     return out[0] != null; 
    } 
    }); 
    return out[0]; 
} 
0

最後我的確從不同的答案如下而工作,讓思路:

public Boolean checkStateSeeking() throws InterruptedException { 
     JavascriptExecutor js = (JavascriptExecutor) driver; 
     Boolean seekingState = (Boolean) js 
       .executeScript("return document.getElementById('vid1_html5').seeking;"); 

     while (seekingState) { 
      // System.out.println(seekingState); 
      seekingState = (Boolean) js 
        .executeScript("return document.getElementById('vid1_html5').seeking;"); 
     } 

     return seekingState; 
    }