What I am trying to accomplish is browsing to a page, waiting for something to load and then taking and saving a screenshot.
The code I already have is
const { By, until } = require('selenium-webdriver');
this.wait = async function (amount: number) {
try {
await this.driver.wait(
until.elementLocated(By.css('[data-test-id="does-not-exist"]')),
amount,
'Looking for element'
);
} catch (e) {
console.log('waiting')
}
We look for a css identifier that isn't there for x amount of seconds. This is typescript btw. This would be a method on some relevant class, or a function by itself. Use it like this
const button = await this.findByCSSSelector('[data-test-id="get-quote-button"]')
const actions = this.driver.actions({ bridge: true });
await actions.move({origin: button }).perform();
// Small pause to observe animation is working correctly in all browsers
await this.wait(700)
const carat = await this.findByCSSSelector('[data-test-id="carat"]');
This waits for .7 of a second so that you can see that whatever animation is working in your functional tests.
You can locate an element that loads after the initial page loads and then make Selenium wait until that element is found.
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("ID")));
If you want to delay a certain number of seconds, rather than to respond as soon as possible, here is a function for pause similar to what selenium IDE offers:
public void pause(Integer milliseconds){
try {
TimeUnit.MILLISECONDS.sleep(milliseconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
source
Just in case it will help somebody, you should always try to avoid implicit waits and especially Thread#sleep
as much as you can. If you do Thread.sleep(10)
, your code will always wait for 10 seconds even in case your page is ready after 1 sec. So this can slow your tests substantially if you use this often.
Better way is to use ExplicitWaits which you means you will wait exactly as long as some action happens or some element gets rendered on the page. So in your case, I would use explicit wait to check whether is everything loaded and then take a screenshot.
That wouldnt really be a selenium specific thing. You just want java to sleep for a bit after loading the page but before taking the screenshot.
Thread.sleep(4000);
put that after your driver.get statement.
Just try this and forget rest! The equivalent of this code can be used in any language. I am writing this in python.
import time
time.sleep(2)
this will make the compiler go to sleep for 2 seconds.