Check if element exists - selenium / javascript / node-js

后端 未结 6 1431
花落未央
花落未央 2020-12-14 12:21

I\'m trying to check if an element exists before I can execute this line:

driver.findElement(webdriver.By.id(\'test\'));

This throws an error \"

相关标签:
6条回答
  • 2020-12-14 13:08

    Why not just use the isElementPresent(locatorOrElement) method? here's a link to the code:

    http://selenium.googlecode.com/git/docs/api/javascript/source/lib/webdriver/webdriver.js.src.html#l777

    0 讨论(0)
  • 2020-12-14 13:10

    The selected answer did not work as expected (err.state was undefined and a NoSuchElementError was always thrown) -- though the concept of using the optional callbacks still works.

    Since I was getting the same error as the OP is referencing, I believe NoSuchElementError should be referenced when determining if the targeted element exists or not. As it's name implies is the error that is thrown when an element does not exist. So the condition in the errorCallback should be:

    err instanceof webdriver.error.NoSuchElementError

    So the complete code block would be as follows (I also am using async/await for those taking advantage of that syntax):

    var existed = await driver.findElement(webdriver.By.id('test')).then(function() {
        return true;//it existed
    }, function(err) {
        if (err instanceof webdriver.error.NoSuchElementError) {
            return false;//it was not found
        } else {
            webdriver.promise.rejected(err);
        }
    });
    //handle value of existed appropriately here
    
    0 讨论(0)
  • 2020-12-14 13:15

    You want to check whether an element exists before you want to find an element on UI. You can wait until the element gets located on UI then you can perform the find element operation.

    Ex: Below code waits until element located then it will perform the find element.

    driver.wait(webdriver.until.elementLocated(webdriver.By.id(LocatorValue)),20000)
    .then(()=>{
       return driver.findElement(webdriver.By.id('test'));
    }).then((element)=>{
        // Perform any operation what you to do.
          return element.click();
    }).catch(()=>{
         console.log('Element not found');
    })
    
    0 讨论(0)
  • 2020-12-14 13:19

    You can leverage the optional error handler argument of then().

    driver.findElement(webdriver.By.id('test')).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);
            }
        });
    

    I couldn't find it explicitly stated in the documentation, but determined this from the function definition in webdriver/promise.js in the selenium-webdriver module source:

      /**
       * Registers a callback on this Deferred.
       * @param {Function=} opt_callback The callback.
       * @param {Function=} opt_errback The errback.
       * @return {!webdriver.promise.Promise} A new promise representing the result
       *     of the callback.
       * @see webdriver.promise.Promise#then
       */
      function then(opt_callback, opt_errback) { 
    
    0 讨论(0)
  • 2020-12-14 13:19

    I know this is a bit late, but this is the code that worked for me.

    var assert = require('assert');
    var expect = require('chai').expect;
    var should = require('chai').should();
    var chai = require('chai');
    var chaiAsPromised = require('chai-as-promised');
    
    chai.use(chaiAsPromised);
    chai.should();
    
    var webdriver = require('selenium-webdriver');
    By = webdriver.By;
    until = webdriver.until;
    
    describe('checking if an element id exists', function() {
    
      it.only('element id exists', function () {
        var driver = new webdriver.Builder().forBrowser('chrome').build();
        driver.get('http://localhost:3000');
        this.timeout(6000);
    
        return driver.wait(until.elementLocated(By.id('idWeWantToTest')), 5 * 1000).then( (e) => {
        }, function(err) {
          throw {
            msg: "element not found"
          }
        }).then( () => {
          driver.quit();
        });     
      });
    })
    
    0 讨论(0)
  • 2020-12-14 13:21

    Here the summary for newbies like me ;-)

    As described here:

    For consistency with the other Selenium language bindings, WebDriver#isElementPresent() and WebElement#isElementPresent() have been deprecated. These methods will be removed in v3.0. Use the findElements command to test for the presence of an element:

      driver.findElements(By.css('.foo')).then(found => !!found.length);
    
    0 讨论(0)
提交回复
热议问题