任何waitForJs函数等待一些javascript代码返回true

时间:2015-01-14 01:42:16

标签: selenium go selenium-webdriver

这是关于golang selenium webdriver的问题。

是否有任何函数仅在某些js代码返回true后返回。

var session *webdriver.Session
...
session.waitForJs(`$('#redButton').css('color')=='red'`)
// next code should be executed only after `#redButton` becomes red

问题是方法session.waitForJs不存在。

1 个答案:

答案 0 :(得分:2)

我没有看到golen绑定到Selenium的任何等待函数,所以你很可能需要定义自己的。这是我第一次尝试golang,所以请耐心等待:

type elementCondition func(e WebElement) bool

// Function returns once timeout has expired or the element condition is true
func (e WebElement) WaitForCondition(fn elementCondition, int timeOut) {

    // Loop if the element condition is not true
    for i:= 0; !elementCondition(e) && i < timeOut; i++ {
        time.sleep(1000)
    }
}

定义elementCondition有两个选项。您使用Javascript的方法看起来可以使用webdriver.go中记录的ExecuteScript函数

  

//将一段JavaScript注入页面中以便执行   当前所选帧的上下文。执行的脚本是   假设是同步的,并且评估脚本的结果是   回到了客户端。

另一种方法是通过Selenium

访问元素属性
func ButtonIsRed(WebElement e) (bool) {
    return (e.GetCssProperty('color') == 'red')
}

所以你的代码会变成

var session *webdriver.Session
....
// Locate the button with a css selector
var webElement := session.FindElement(CSS_Selector, '#redButton')
// Wait for the button to be red
webElement.WaitForCondition(ButtonIsRed, 10)