Gabe D.
Gabe D.

Reputation: 59

How to run selenium webdriver code once element is present

Everything I've seen over the past month of looking is outdated. Here's my problem, I traverse through about 5 different pages on one website before I get to the data I need. I can't fire off a driver.get as the url stays the same for all 5 different pages.

Since Node.js is asynchronous it runs the code before the element is present. I realize I could use a timeout, but i'm running this code 100's of times so a timeout won't work.

Everyone online says to do this, but it's outdated and doesn't work:

driver.findElement(By.css('#gridsortlink')).then(function(webElement) {
webElement.isElementPresent(By.css('#gridsortlink'))
.then(function(found) { console.log(found); });
});

If you do know how to do this that'd be great as I've been looking for a month now for the solution.

Upvotes: 1

Views: 176

Answers (3)

Vivek Bhatt
Vivek Bhatt

Reputation: 40

Java code:

if((driver.findElements(By.css('#gridsortlink')).size())==1)    
{
system.out.println(executecode);
}
else
{
system.out.println(element is not exist in webpage);
}

You can check element is present or not.

driver.findElements(By.css('#gridsortlink')).size() this row returns to 0 or 1.

1 means - Element exists on webpage.

0 means - Element does not exist on webpage.

Try in your code.

Upvotes: 0

Bhupesh
Bhupesh

Reputation: 231

In place of webElement.isElementPresent try to use driver.isElementPresent

driver.findElement(By.css('#gridsortlink')).then(function(webElement) {
driver.isElementPresent(By.css('#gridsortlink'))
.then(function(found) { console.log(found); });
});

I don't have access to your application thats why I created a demo code for gmail where I am putting some wrong value in Email field and after some time I am getting an error message. and the output here is 'true'.

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().forBrowser('chrome').build();
var By = webdriver.By;
driver.get('http://gmail.com');

driver.findElement(By.id("Email")).then(function(emailText){
   emailText.sendKeys("aaaaaaaaaaaaaaaaaaaaaaaaaadddddddddddd").then(function(){
     driver.findElement(By.id("next")).then(function(submit){
        submit.click().then(function(){
             driver.isElementPresent(By.className("error-msg")).then(function(text){
                console.log(text);
             });
        });
     });
   });
}); 

Upvotes: 0

Saurabh Gaur
Saurabh Gaur

Reputation: 23845

Your tried attempt looks incorrect, you should try as below :-

var webdriver = require('selenium-webdriver'),
    By = webdriver.By,
    until = webdriver.until;

driver.wait(until.elementLocated(By.css('#gridsortlink')), 5 * 1000).then(function(found) {
    console.log(found);
});

Upvotes: 1

Related Questions