Selenium needs a sleep before going to the next page

前端 未结 2 1006
心在旅途
心在旅途 2020-12-12 05:06

I am currently learning Selenium, and I learned a lot. One thing the community said; is that you need avoiding thread.sleep as much as possible. Selenium uses implicit and e

2条回答
  •  余生分开走
    2020-12-12 05:26

    As per your question and the updated comments It raises an exception that it can't find the element on the webpage, it is very much possible. Additionally when you mention putting a sleep in between is not an elegant solution to fix, that's pretty correct as inducing Thread.sleep(1000); degrades the overall Test Execution Performance.

    Now, what I observed in your commented code block to compare document.readyState to complete was a wiser step. But sometime it may happen that, though Web Browser will send document.readyState as complete to Selenium, due to presence of JavaScript and AJAX Calls the elements with whom we want to interact may not be Visible, Clickable or Interactable which in-turn may raise associated Exception.

    So, the solution would be inducing ExplicitWait i.e. WebDriverWait. We will induce ExplicitWait for the element with which we want to interact, with proper ExpectedConditions set. You can find documentation about ExplicitWait here.

    An Example:

    If you want to wait for a button to be clickable the expected code block may be in the following format along with the imports:

    import org.openqa.selenium.By;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;        
    
    // Go to second page and wait for the element    
    WebDriverWait wait = new WebDriverWait(driver, 10);
    wait.until(ExpectedConditions.elementToBeClickable(By.id("id_of_the_element")));        
    //perform actions
    driver.navigate().to(URL + "/mymp/verkopen/index.html");
    

提交回复
热议问题