在Node.js中检查Selenium时出错

时间:2015-06-02 14:50:23

标签: javascript node.js selenium

我有这个代码块,应该检查一个元素是否在页面上,如果它应该输出给定的消息。如果不是,它应该输出错误信息。我无法正确检查我的元素。我应该创建一个对象还是一个数组?如果是这样,我如何检查其中的多个值?

var e1 = 'search';
var e2 = 'success';

driver.findElement(webdriver.By.className(e1, e2)).then(function(webElement) {
    console.log('The elements ' +
                '"' + e1 + '",' +
                '"' + e2 + '"' + 'are present.');

}, function(err) {
    if (err.state && err.state === 'no such element') {
        console.log('The element ' + '"' + e1 + '"' + ' is NOT found.');
    } else {
        webdriver.promise.rejected(err);
    }
});

编辑:使用Wilsons代码

var destinationStarlet = 'log';

var URL = 'http://localhost:8888/' + destinationStarlet;

var a = '.nav';
getElementByCss(URL, driver, a, onResult);

var b = '.advanced-search';
getElementByCss(URL, driver, b, onResult);


function onResult(err, element) {
if (err) {
    return console.log(err.message);
}

element.getText()
    .then(

function (presentText) {

});
}

driver.sleep(10000);

function getElementByCss(URL, driver, css, cb) {
function error(err) {
    if (err.name === 'NoSuchElementError') {
        err.message = 'The element "' + css + '" was NOT found.';
    }

    cb(err);
}

function elementFound(element) {
     console.log('The element ' + '"' + css + '"' + ' is present!');

    cb(null, element);
}

function siteLoaded() {
    driver.findElement({
        css: css
    })
        .then(elementFound, error);
}

driver.get(URL)
    .then(siteLoaded)
}

1 个答案:

答案 0 :(得分:0)

我们假设我们正在检查这个HTML

enter image description here

我们想知道div.buttons中的按钮是否存在:

var URL = 'http://some-web-site';

var myButtonCSS = '.buttons #my-button';
var myAnotherButtonCSS = '.buttons #my-another-button';
var myThirdButtonCSS = '.buttons #my-third-button';

getElementByCss(URL, driver, myButtonCSS, onResult); // exist
getElementByCss(URL, driver, myAnotherButtonCSS, onResult); // exist
getElementByCss(URL, driver, myThirdButtonCSS, onResult); // does not exist

function onResult (err, element) {
  if (err) {
    return console.log(err.message);
  }

  element
    .getText()
    .then(
      function (buttonText) {
        console.log(buttonText);
      }
    );
}

我创建了一个实用程序函数,允许您通过css搜索元素:

function getElementByCss (URL, driver, css, cb) {
    function error (err) {
      if (err.name === 'NoSuchElementError') {
        err.message = 'Element at "' + css + '", was not found.';
      }

      cb(err);
    }

    function elementFound (element) {
      cb(null, element);
    }

    function siteLoaded () {
      driver
        .findElement({
          css: css
        })
        .then(elementFound, error);
    }

    driver
      .get(URL)
      .then(siteLoaded)
}