如何在 WebDriverJS 中等待元素可点击? [英] How do I wait for an element to be clickable in WebDriverJS?

查看:35
本文介绍了如何在 WebDriverJS 中等待元素可点击?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道如何在 WebDriverJS 中等待 WebElement 可点击?我已经知道如何等待元素可见",但我需要它可点击".. 类似于 预期条件.我在 Webdriver Js API 中找不到类似的东西.

Does anybody know how to wait for a WebElement to be clickable in WebDriverJS? I already know how to wait for the element to be "visible", but I would need it to be "clickable".. Something similar to expectable conditions in Python binding. I haven't been able to find something similar in Webdriver Js API.

推荐答案

似乎没有条件等同于 Python 的 selenium.webdriver.support.expected_conditions.element_to_be_clickable.但是,查看该条件的来源,我发现它进行了两项检查:

There does not seem to be a condition equivalent to Python's selenium.webdriver.support.expected_conditions.element_to_be_clickable. However, looking at the source for that condition, I see that it does two checks:

  1. 该元素是可见的.

  1. That the element is visible.

已启用.

所以你可以等待这两个条件都成立.以下代码说明了如何做到这一点.它首先使一个元素不可见并禁用它,设置一些超时以使其可见并启用它,然后等待两个条件发生.

So you could wait for both conditions to become true. The following code illustrates how that could be done. It first make an element invisible and disables it, sets some timeouts to make it visible and enable it, and then wait for the two conditions to happen.

var webdriver = require('selenium-webdriver');

var driver = new webdriver.Builder().
   withCapabilities(webdriver.Capabilities.chrome()).
   build();

driver.get('http://www.google.com');

// This script allows testing the wait. We make the element invisible
// and disable it and then set timeouts to make it visible and enabled.
driver.executeScript("\
var q = document.getElementsByName('q')[0];\
q.style.display = 'none';\
q.disabled = true;\
setTimeout(function () {\
    q.style.display = '';\
}, 2000);\
setTimeout(function () {\
    q.disabled = false;\
}, 3000);\
");
driver.findElement(webdriver.By.name('q')).then(function (element) {
    driver.wait(function () {
        return element.isDisplayed().then(function (displayed) {
            if (!displayed)
                return false;

            return element.isEnabled();
        });
    });
    element.sendKeys('webdriver');
});
driver.findElement(webdriver.By.name('btnG')).click();
driver.wait(function() {
 return driver.getTitle().then(function(title) {
   return title === 'webdriver - Google Search';
 });
}, 1000);

driver.quit();

由于我们使用的是 promise,代码看起来可能有点奇怪.并不是说 Promise 本质上很奇怪,但是当人们习惯使用 Python 时,它们需要一些时间来适应.

The code may look a bit strange due to the fact that we're working with promises. Not that promises are inherently strange but they take some time getting accustomed to when one is used to work with Python.

这篇关于如何在 WebDriverJS 中等待元素可点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆