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)
-
1This looks to be very similar to this question with the latest answer (April 6, 2017) showing the best solution: stackoverflow.com/a/43263908/3817795Swagin9– Swagin92017年06月06日 14:07:15 +00:00Commented Jun 6, 2017 at 14:07
2 Answers 2
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.
-
Do you have a reference to the ExpectedConditions class? I found the Until class seleniumhq.github.io/selenium/docs/api/javascript/module/…. Is that something different?jmreicha– jmreicha2016年10月13日 21:37:21 +00:00Commented Oct 13, 2016 at 21:37
-
I was able to get the code working with
ExpectedConditions
in Python but not in Javascript :(jmreicha– jmreicha2016年10月14日 00:11:52 +00:00Commented Oct 14, 2016 at 0:11
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);
-
1I'm using Javascript, not Java.jmreicha– jmreicha2016年10月14日 15:52:36 +00:00Commented Oct 14, 2016 at 15:52
Explore related questions
See similar questions with these tags.