2017-01-09 40 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; 
    }