2012-03-28 118 views
8

我想獲得頁面加載的例外,但是還沒有結果。 我使用implicitlyWait來設置定時器來拋出異常。Java WebDriver等待頁面加載

WebDriver driver = new FirefoxDriver(); 
driver.manage().timeouts().implicitlyWait(1, TimeUnit.MILLISECONDS); 
driver.get("http://www.rambler.ru"); 
driver.quit(); 

有人請更新我的建議嗎?我需要這個來確保頁面加載不會是無限的,如果加載的時間會超過我在定時器中定義的 - >拋出異常作爲結果並跳過TC(失敗)。

謝謝 沃洛

回答

17

你爲什麼要使用隱式等待頁面打開之前?嘗試使用明確的等待。在ramber中找到一些主要的頁面元素(例如,搜索文本框)。例如:

WebDriverWait wait = new WebDriverWait(webDriver, 5); 
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("xpath_to_search_textbox"))); 

直到()方法將拋出TimeoutException,如果搜索文本框不會在5秒內出現。

+0

謝謝你的建議,糾正我,如果我錯了,你建議我在driver.get(「http://www.rambler.ru」)後使用等待元素。但WebDriver將等待,直到driver.get()將完成頁面加載,並將轉到元素等待? – 2012-03-28 11:00:46

+0

webdriver總是等待加載頁面。可能是我對你的問題有錯誤的理解。在這種情況下,如果加載時間超過30秒(例如) – 2012-03-28 11:13:38

+0

我的意思是:http:// stackoverflow .com/a/6107997/1165331 – 2012-03-28 11:18:54

0

我不同意帕維爾佐林斯的答案將工作,因爲他沒有展示如何處理例外。

下面是我如何等待iFrame。這要求你的JUnit測試類通過RemoteWebDriver實例到頁面對象:

public class IFrame1 extends LoadableComponent<IFrame1> { 

    private RemoteWebDriver driver; 

    @FindBy(id = "iFrame1TextFieldTestInputControlID") 
    public WebElement iFrame1TextFieldInput; 

    @FindBy(id = "iFrame1TextFieldTestProcessButtonID") 
    public WebElement copyButton; 

    public IFrame1(RemoteWebDriver drv) { 
     super(); 
     this.driver = drv; 
     this.driver.switchTo().defaultContent(); 
     waitTimer(1, 1000); 
     this.driver.switchTo().frame("BodyFrame1"); 
     LOGGER.info("IFrame1 constructor..."); 
    } 

    @Override 
    protected void isLoaded() throws Error {   
     LOGGER.info("IFrame1.isLoaded()..."); 
     PageFactory.initElements(driver, this); 
     try { 
      assertTrue("Page visible title is not yet available.", driver 
    .findElementByCssSelector("body form#webDriverUnitiFrame1TestFormID h1") 
        .getText().equals("iFrame1 Test")); 
     } catch (NoSuchElementException e) { 
      LOGGER.info("No such element."); 
      assertTrue("No such element.", false); 
     } 
    } 

    @Override 
    protected void load() { 
     LOGGER.info("IFrame1.load()..."); 
     Wait<WebDriver> wait = new FluentWait<WebDriver>(driver) 
       .withTimeout(30, TimeUnit.SECONDS) 
       .pollingEvery(5, TimeUnit.SECONDS) 
       .ignoring(NoSuchElementException.class) 
       .ignoring(StaleElementReferenceException.class) ; 
      wait.until(ExpectedConditions.presenceOfElementLocated( 
      By.cssSelector("body form#webDriverUnitiFrame1TestFormID h1"))); 
    } 
.... 

注意:您可以see my entire working example here