Search code examples
javaselenium-webdriverxpathcss-selectorswebdriver-w3c-spec

How to speed up Java Selenium Script,with minimum wait time


I'm currently working on a java selenium Project, which is usually a small script where I have to check for each element for it's presence and based on that some actions are triggered but our main concern is time duration to finish the script.

Basically I have used each one from below in my script and ran the test, though in each case script was running but I find very little speed improvement in script execution duration.I'm using wait

driver.manage().timeouts().implicitlyWait(10000,TimeUnit.MILLISECONDS);

and along with it

!(driver.findElement(By.xpath("Element Xpath)).isEmpty()) 

or

driver.findElements(By.xpath("Element Xpath)).size()>0

I know I can go for CSS Selectors but in my case that is not feasible due to DOM Tree structure. what can be used instead of

driver.findElements(By.xpath("Element Xpath)).size()>0

this to check if element is present or not and based on that I have to trigger multiple other actions.


Solution

  • There are a few issues with your approach.

    1. .implicitlyWait() doesn't actually wait. It sets the timeout for the driver instance so you only need to set it once, not call it each time you want to wait.

    2. driver.findElement(...).isEmpty() won't compile. Maybe you meant .findElements()? Either way, .isEmpty() vs .size() > 0 is going to be a negligible difference in speed.

    3. The main problem is that you have an implicit wait enabled when checking for something to NOT be present... especially a 10s wait. That means that each time an element is checked for, Selenium will wait for 10s even if it's expecting it to NOT be there.

    You would be better served by turning off implicit wait (setting it to 0) and then do your existence check for elements you expect not to be there and then turn it back on. That will be 10s x # of existence checks you expect to not be there. Depending on how many existence checks you do, that could add up to a LOT of time. One downside of this, if you have a complex page with background processes, you will need to have a specific wait for the page (or portion of a page) to finish loading before checking for existence of elements with implicit wait off.

    Side note... Selenium contributors have stated that implicit waits shouldn't be used period. Use WebDriverWait instead but that's a whole other discussion.