3

I'm new to Selenium and I think I'm just not understanding what is happening in the code and browser. I can work around my issue by replacing the driver.wait code (posted below) with a driver.sleep(1000) but I have been reading that sleep statements aren't ideal.

Can somebody help me figure out why the code I have isn't working and what exactly is going on? I can provide a full stack trace if it is helpful.

Here is what the code looks like.

const webdriver = require('selenium-webdriver')
const chrome = require("selenium-webdriver/chrome");
const By = webdriver.By
const until = webdriver.until

var username = "XXX"
var password = "XXX"

function login(username, password) {    
    // This part works fine
    driver.wait(until.elementLocated(By.id('Email')))
    driver.findElement(By.id('Email')).sendKeys(username)
    driver.findElement(By.id('next')).click()

    // Here is where the element not visible happens
    driver.wait(until.elementLocated(By.id('Passwd')), 5000)
    // driver.sleep(1000) works but I'm not sure why?
    driver.findElement(By.id('Passwd')).sendKeys(password)

    // Login
    driver.findElement(By.id('signIn')).click()
}

var driver = new webdriver.Builder()
        .withCapabilities({'browserName': 'chrome'}).build()
driver.get('https://gmail.com')
login(username, password)
3

You are right, Selenium allows you to avoid such woodoo waits, gives you full control. And you know the drill: "with great power comes great responsibility". So:

1) learn to use helper class ExpectedConditions: EC.presence_of_element_located() - will wait until element is visible and clickable

2) Once you located element, save reference and use it, so you don't have to locate in next line again.

-1

My solution:

  • You are saying is correct. In best practices we should avoid using explicit wait driver.sleep(5000)

  • Try to use implicit wait which will not wait unnecessarily. See below method:

     public void waitForElement(WebElement value)
     {
         // wait for field
         WebDriverWait wait = new WebDriverWait(driver, 90);
    
         wait.until(ExpectedConditions.visibilityOf(value));
         System.out.print("."); // Just to verify code is used and working   
     }
    
  • Actual Use:

    waitForElement(obj.your_web_element);
    
  • 1
    I'm using Javascript, not Java. – jmreicha Oct 14 '16 at 15:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.