Selenium在提交后不等待网站加载

时间:2016-11-24 22:08:57

标签: c# selenium selenium-webdriver

我正在尝试使用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);
    }
}

2 个答案:

答案 0 :(得分:2)

我发现执行此操作的最佳方法是等待第一页上的元素过时,然后等待新页面上的元素。您可能遇到的问题是您正在等待body元素...它将存在于每个页面上。如果您只想等待一个元素,您应该找到一个元素,该元素对于您要导航到的页面是唯一的。如果你仍想使用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);
}

答案 1 :(得分:0)

回答几乎是在JeffC的回答中:

  

我发现最好的方法是等待第一页上的元素过时,然后等待新页面上的元素。

我用这个答案解决了这个问题:https://stackoverflow.com/a/15142611/5819671

我在从新页面读取body元素之前放下以下代码,现在它可以工作:

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