zakaria kasmi
zakaria kasmi

Reputation: 509

How can I wait for page load in selenium before moving to another page? (C#)

I am kinda new to selenium, basically, what I am trying to do is login to website1, wait until the page is fully loaded. And move to website2. I don't want to use Thread.Sleep() as you know this will make my UI unresponsive. How can I make that using selenium with c#.

        MyWebDriver.Navigate().GoToUrl(url1);
        MyWebDriver.FindElement(By.Name(Username_Input)).SendKeys(username);
        MyWebDriver.FindElement(By.Name(Password_Input)).SendKeys(password);
        MyWebDriver.FindElement(By.XPath(Log_in_Button)).Click();
        //wait untill the page is fully loaded then move to url2
        MyWebDriver.Navigate().GoToUrl(url2);

I found an answer which is using ExpectedConditions.ElementIsVisible but unfortunately I can't find ExpectedConditions in the new selenium version.

Upvotes: 1

Views: 7763

Answers (3)

Vincent
Vincent

Reputation: 524

bool wait = new WebDriverWait(Driver, TimeSpan.FromSeconds(60)).Until(d => ((IJavaScriptExecutor)d).ExecuteScript("return document.readyState").Equals("complete")); 

if(wait == true)
{
    //Your code
}

Above code will wait for page to load for 60 seconds and return true if page is ready(within 60 seconds), false if page is not ready (after 60 seconds).

Upvotes: 3

Deepan
Deepan

Reputation: 119

As DebanjanB said we no need to wait for complete page load. Rather you can try below method:

MyWebDriver.Navigate().GoToUrl(url2);
WebDriverWait wait = new WebDriverWait(dr, TimeSpan.FromMinutes(5));
element = wait.Until(ExpectedConditions.ElementToBeClickable(dr.FindElement(By.Name("User_Name"))));

Upvotes: 2

undetected Selenium
undetected Selenium

Reputation: 193058

Fundamentally as a part of a validation process you don't wait for a page to load, rather you wait to verify the end result of an action either in terms of :

  • An ElementIsVisible
  • An ElementToBeClickable
  • Some TextToBePresentInElement
  • The TitleContains
  • The UrlContains
  • etc

    So your Automation Script will be validating any of the above mentioned validation points.

    As per the API Docs (C#) the ExpectedConditions Class does mentions about the method ElementIsVisible as follows :

ExpectedConditions.ElementIsVisible Method

An expectation for checking that an element is present on the DOM of a page and visible. Visibility means that the element is not only displayed but also has a height and width that is greater than 0.

  • Namespace: OpenQA.Selenium.Support.UI
  • Assembly: WebDriver.Support (in WebDriver.Support.dll) Version: 3.1.0
  • Parameters (locator) :
    • Type : OpenQA.Selenium.By
    • Return Value : Type: Func<IWebDriver, IWebElement>

Screenshot :

ElementIsVisible

Upvotes: 1

Related Questions