这是关于 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
方法不存在。
最佳答案
我在与 Selenium 的 golang 绑定(bind)中没有看到任何等待函数,因此您很可能需要定义自己的函数。这是我第一次尝试 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
函数一起使用
// Inject a snippet of JavaScript into the page for execution in the context of the currently selected frame. The executed script is assumed to be synchronous and the result of evaluating the script is returned to the client.
另一种方法是通过 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)
关于selenium - 任何等待某些 javascript 代码的 waitForJs 函数返回 true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27934554/