Selenium WebDriver等到元素显示

时间:2014-09-09 20:22:53

标签: javascript node.js selenium-webdriver

我在谷歌和SO网站上搜索过,我得到了JAVA的答案,但似乎没有得到node.js的答案

我有一个需要时间加载的网络应用。我会让selenium程序等到页面加载然后执行一些操作。

我目前的代码如下

//dependencies
var webdriver = require('selenium-webdriver'),
    util = require('util'),
    _ = require('underscore');

var driver = new webdriver.Builder().withCapabilities(webdriver.Capabilities.chrome()).build();
var branchName =  _.isUndefined(process.argv[3]) ? 'branch' : process.argv[3], 
    hostName = _.isUndefined(process.argv[2]) ? 'localhost' : process.argv[2],
    appTmpl = 'http://%s/%s',
    username = 'xxxx',
    password = 'xxxx';
var appUrl = util.format(appTmpl, hostName, branchName);

driver.get(appUrl);
driver.findElement(webdriver.By.name("username")).sendKeys(username);
driver.findElement(webdriver.By.name("password")).sendKeys(password);
driver.findElement(webdriver.By.name("login_button")).click();
driver.quit();

我得到的错误是:

    C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:1643
      throw error;
            ^
NoSuchElementError: no such element
  (Session info: chrome=37.0.2062.103)
  (Driver info: chromedriver=2.10.267521,platform=Windows NT 6.1 SP1 x86_64)
    at new bot.Error (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\atoms\error.js:109:18)
    at Object.bot.response.checkResponse (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\atoms\response.js:106:9)
    at C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:277:20
    at C:\Work\study\selenium\node_modules\selenium-webdriver\lib\goog\base.js:1243:15
    at webdriver.promise.ControlFlow.runInNewFrame_ (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:1539:20)
    at notify (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:362:12)
    at notifyAll (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:331:7)
    at resolve (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:309:7)
    at fulfill (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:429:5)
    at C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\promise.js:1406:10
==== async task ====
WebDriver.findElement(By.name("username"))
    at webdriver.WebDriver.schedule (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:268:15)
    at webdriver.WebDriver.findElement (C:\Work\study\selenium\node_modules\selenium-webdriver\lib\webdriver\webdriver.js:711:17)
    at Object.<anonymous> (C:\Work\study\selenium\test.js:15:8)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)

9 个答案:

答案 0 :(得分:41)

我偶然发现了我的问题的答案

所以等待元素出现我们必须:

driver.wait(function () {
    return driver.isElementPresent(webdriver.By.name("username"));
}, timeout);

答案 1 :(得分:28)

您可以使用webdriver.wait

then()上注册听众
return driver.wait(until.elementLocated(By.name('username')), 5 * 1000).then(el => {
    return el.sendKeys(username);
});

答案 2 :(得分:18)

您不需要自定义功能,您可以这样做:

  let el = await driver.findElement(By.id(`import-file-acqId:${acqId}`));
  await driver.wait(until.elementIsVisible(el),100);
  await el.sendKeys(file);

请参阅此处的文档:

https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/until.html

答案 3 :(得分:3)

尝试这样的事情:

function isItThere(driver, element){

    driver.findElement(webdriver.By.id(element)).then(function(webElement) {
            console.log(element + ' exists');
        }, function(err) {
            if (err.state && err.state === 'no such element') {
                console.log(element + ' not found');
            } else {
                webdriver.promise.rejected(err);
            }
        });
}

我根据我在这里找到的内容稍微调整了一下:Check if element exists - selenium / javascript / node-js它有点魅力。

答案 4 :(得分:2)

这是唯一对我有用的东西:

const element = By.id('element');
driver.wait(until.elementLocated(element));
const whatElement = driver.findElement(element);
driver.wait(until.elementIsVisible(whatElement), 5000).click();

答案 5 :(得分:1)

我通常使用这种方式:

 var el = driver.wait(until.elementLocated(By.name('username')));
el.click();

答案 6 :(得分:0)

编写异步功能以避免此问题

(async function() {
  let url = args[0];
  await driver.get(url);
  driver.quit();
})();

答案 7 :(得分:0)

我想出了这种方法,因为它保持了可链接的promise语法,因此我可以这样写:await waitFind(By.id('abc')).click()

const waitFind = (locator) => {
    return driver.findElement(async () => {
        await driver.wait(until.elementLocated(locator));
        return driver.findElement(locator);
    });
}

答案 8 :(得分:0)

主要问题是webdriver认为元素已经存在,但还没有。我有一个解决方案,很丑但是可以。在网络驱动程序认为有项目之后,请尝试单击。 收到错误消息:

StaleElementReferenceError: stale element reference: element is not attached to the page document  (Session info: chrome=83.0.4103.106)

没问题,在循环中等待500ms,然后尝试再次单击。在我的情况下,尝试5次就足够了,大约2-3次点击即可成功。

async clickonitem( driver, itemname ) {
    const strftime = require('strftime');
    var trycounter = 0;
    var timeout = 500;
    var success;
    do {
      try {
        trycounter++;
        success = true;
        console.log( strftime('%F %T.%L'), "Finding #" + trycounter + " " + itemname );
        var item = await driver.wait( until.elementLocated( By.xpath( '//input[@name="' + itemname +'"]' ) ), 
                        timeout );
        console.log( strftime('%F %T.%L'), "Found or Timeout #" + trycounter );
        //await item.click();
        await driver.wait( item.click(), 
                        timeout );
        console.log( strftime('%F %T.%L'), "Click #" + trycounter + " " + itemname );
      } 
      catch(err) {
        success = false;
        //this.log( "Error #" + trycounter + " " + itemname + "\n" +err );
        this.log( strftime('%F %T.%L'), "Error #" + trycounter + " " + itemname + " waiting: " + timeout );
        await wait( timeout );
        continue;
      }

    } while( !success && trycounter < 5 );
}       
        async wait( ms ) {
          return new Promise((resolve) => {
            setTimeout(resolve, ms);
          });
        }

clickonitem( driver, "login_button" );