2016-11-24 72 views
1

我想提交一個來自C#Selenium的登錄表單。但是在提交之後,我無法等待加載新頁面。唯一有效的是Thread.Sleep。我應該怎麼做才能讓它等待?硒提交後不等待,直到網站被加載

[TestFixture] 
public class SeleniumTests 
{ 
    private IWebDriver _driver; 

    [SetUp] 
    public void SetUpWebDriver() 
    { 
     _driver = new FirefoxDriver(); 

     // These doesn't work 
     //_driver.Manage().Timeouts().SetPageLoadTimeout(TimeSpan.FromSeconds(10)); 
     //_driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(10)); 
    } 

    [Test] 
    public void SubmitTest() 
    { 
     _driver.Url = "http://mypage.com"; 

     _driver.FindElement(By.Name("username")).SendKeys("myname"); 
     _driver.FindElement(By.Name("password")).SendKeys("myeasypassword"); 
     _driver.FindElement(By.TagName("form")).Submit(); 

     // It should wait here until new page is loaded but it doesn't 

     // So far this is only way it has waited and then test passes 
     //Thread.Sleep(5000); 

     var body = _driver.FindElement(By.TagName("body")); 
     StringAssert.StartsWith("Text in new page", body.Text); 
    } 
} 
+1

這是'geckodriver'的一個已知的問題: https://github.com/mozilla/geckodriver/issues/308 –

+0

如果'Thread.Sleep()'不起作用,你還試過了什麼?隱式/顯式等待將是我尋找解決方案的第一站。 –

+0

Thread.Sleep的作品。但我想有更好的解決方案。 –

回答

1

我發現最好的辦法是等待第一頁上的元素過時,然後等待新頁面上的元素。你可能遇到的問題是,你正在等待身體元素......這將存在於每一頁上。如果您只想等待某個元素,則應該找到您要導航到的頁面所特有的元素。如果你仍然想使用body標籤,你可以做到這一點...

public void SubmitTest() 
{ 
    _driver.Url = "http://mypage.com"; 

    _driver.FindElement(By.Name("username")).SendKeys("myname"); 
    _driver.FindElement(By.Name("password")).SendKeys("myeasypassword"); 
    IWebElement body = _driver.FindElement(By.TagName("body")); 
    _driver.FindElement(By.TagName("form")).Submit(); 

    body = new WebDriverWait(_driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(By.TagName("body"))) 
    StringAssert.StartsWith("Text in new page", body.Text); 
} 
0

答案是幾乎在JeffC的回答是:

我發現做到這一點的最好辦法就是等待要使第一頁上的元素過時,請等待新頁面上的元素。

我解決了這個這樣的回答:https://stackoverflow.com/a/15142611/5819671

閱讀來自新的頁面主體元素在我把下面的代碼,現在,它的工作原理:

new WebDriverWait(_driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementExists((By.Id("idThatExistsInNewPage"))));