selenium - 任何等待某些 javascript 代码的 waitForJs 函数返回 true

标签 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 方法不存在。

最佳答案

我在与 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/

相关文章:

javascript - PHPUnit-Selenium - 如何执行 javascript

java - 无法在 Windows 10 的 docker 上拉取 selenium/hub 镜像

generics - 如何使结构字段成为泛型类型

go - 如何在不牺牲内存的情况下组织类似的结构以避免重复

dataframe - 如何编码和解码或转换对象,同时避免在 golang 中键入

Python-3.x-Selenium : Changing the used driver while staying logged in on a website

testing - Sikuli 与 Selenium WebDriver 的集成

java - element.getText() 方法在 java selenium 中不起作用

javascript - Selenium JavaScript - 将元素滚动到 View 中而不与标题重叠

java - By.xpath(contains(text(), "Some text") 给出错误