javaselenium-webdriverhtmlunit-driver

How can I wait a page to load with selenium htmlunitDriver?


I am working on a bot for a page similar to Ad.fly. After opening the link, I want to wait five seconds for the page to load before the button to click appears.

I want to execute this with HtmlunitDriver. I tried with implicit wait and explicit wait, but that did not work. Somebody told me to use FluentWait, but I don't know how to implement it.

Here is my actual code, can someone help me understand how to implement FluentWait?

public class bot {

public static WebDriver driver;
public static void main(String[] args) {
     driver = HtmlUnitDriver();
     driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
     driver.get("http://bc.vc/xHdGKN");
     // HERE I HAVE TO USE FLUENT WAIT, SOMEBODY MAY EXPLAIN TO ME?
     driver.findElement(By.id("skip_btn")).click(); // element what i have to do click when the page load 5 seconds "skip ads button"
}

}

I would like a good method to apply... I will be grateful if you help :)


Solution

  • Actually, FluentWait is more suitable for a situation where the wait can range widely, let say anytime between 1 to 10 seconds. For example:

    Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)
            .withTimeout(10, TimeUnit.SECONDS)
            .pollingEvery(1, TimeUnit.SECONDS)
            .ignoring(NoSuchElementException.class);
    
    WebElement el = wait.until(new Function<WebDriver, WebElement>() {
        public WebElement apply(WebDriver driver) {
            return driver.findElement(By.id("skip_btn"));
        }
    });
    
    el.click();
    

    Just to be sure, these are the import statements that you need:

    import com.google.common.base.Function;
    import org.openqa.selenium.By;
    import org.openqa.selenium.NoSuchElementException;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.ui.FluentWait;
    import org.openqa.selenium.support.ui.Wait;
    import java.util.concurrent.TimeUnit;