Wait for page load in Selenium

后端 未结 30 2764
攒了一身酷
攒了一身酷 2020-11-22 07:12

How do you make Selenium 2.0 wait for the page to load?

30条回答
  •  独厮守ぢ
    2020-11-22 08:18

    SeleniumWaiter:

    import com.google.common.base.Function;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.WebElement;
    import org.openqa.selenium.support.ui.WebDriverWait;
    
    public class SeleniumWaiter {
    
          private WebDriver driver;
    
          public SeleniumWaiter(WebDriver driver) {
               this.driver = driver;
          }
    
          public WebElement waitForMe(By locatorname, int timeout){
               WebDriverWait wait = new WebDriverWait(driver, timeout);
               return wait.until(SeleniumWaiter.presenceOfElementLocated(locatorname));
          }
    
          public static Function presenceOfElementLocated(final By locator) {
                // TODO Auto-generated method stub
                return new Function() {
                     @Override
                     public WebElement apply(WebDriver driver) {
                          return driver.findElement(locator);
                     }
                };
          }
     }
    

    And to you use it:

    _waiter = new SeleniumWaiter(_driver);
    
    try {
       _waiter.waitForMe(By.xpath("//..."), 10);
    } 
    catch (Exception e) {
       // Error
    }
    

提交回复
热议问题