Implementing wait functionality in Selenium using C# is essential for ensuring your tests

I've been tasked with writing Selenium C# code to log in to a website and check that the loading time is under 10 seconds. The challenge is that I'm not allowed to use any waiting functions, and since it's a login process, I don't have a URL to work with. I haven't been able to find a solution without using a wait function. Can anyone point me in the right direction or provide a focused tutorial?

Here's what I tried, but it wasn't accepted:

static WebDriver Login()
{
    WebDriver driver = new ChromeDriver();
    driver.Navigate().GoToUrl(URL);
    driver.FindElement(By.Id(ID_USERNAME)).SendKeys(USERNAME);
    driver.FindElement(By.Id(ID_PASSWORD)).SendKeys(PASSWORD);
    driver.FindElement(By.Id(ID_BUTTON_LOGIN)).Click();
    return driver;
}

static void CheckLoginTime(WebDriver driver)
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(TIME_TO_LOAD_SECONDS));
    long time1 = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
    wait.Until(ExpectedConditions.ElementIsVisible(By.Id(ID_ACCOUNT_LINK)));
    long time2 = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
    if (time2 - time1 >= TIME_TO_LOAD_SECONDS * 1000)
    {
        throw new Exception("Login time exceeded 10 seconds");
    }
}

static void CheckLogout(WebDriver driver)
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(TIME_TO_LOAD_SECONDS));
    wait.Until(ExpectedConditions.ElementIsVisible(By.Id(ID_ACCOUNT_LINK)));

    driver.FindElement(By.Id(ID_ACCOUNT_LINK)).Click();
    driver.FindElement(By.Id(ID_LOGOUT)).Click();
    driver.FindElement(By.Id(ID_OK_LOGOUT)).Click();

    wait = new WebDriverWait(driver, TimeSpan.FromSeconds(TIME_TO_LOAD_SECONDS));
    wait.Until(ExpectedConditions.ElementIsVisible(By.CssSelector(SELECTOR_HOVER)));
    string text = driver.FindElement(By.CssSelector(SELECTOR_HOVER)).GetAttribute("title");
    string path = Directory.GetCurrentDirectory();
    using (StreamWriter writer = new StreamWriter(path + FILE_NAME))
    {
        writer.WriteLine(text);
    }
}

static void Main(string[] args)
{
    WebDriver driver = Login();
    CheckLoginTime(driver);
    CheckLogout(driver);

}

Answer №1

Here is a possible solution utilizing a simple "busy wait" loop:

static void CheckLoginTime(WebDriver driver)
        {
            long start = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
            bool found = false;
            while (!found)
            {
                try
                {
                    driver.FindElement(By.Id(hashVarData["ID_ACCOUNT_LINK"]));
                }
                catch (Exception e)
                {
                    continue;
                }
                found = true;
            }
            long end = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
            Console.WriteLine("Execution time: " + (end - start));
            if (end-start >= Int32.Parse(hashVarData["TIME_TO_LOAD_SECONDS"]) * 1000)
            {
                throw new Exception("Login time exceeded 10 seconds");
            }
        }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating simple Java programs utilizing the Selenium WebDriver

As a beginner Java programmer looking to familiarize myself with Selenium libraries, I have been searching Google for a good resource to learn basic Selenium programming. Despite my efforts, I have not been able to find the right place to start. Can anyone ...

Tips for extracting a website's dynamic HTML content after AJAX modifications using Perl and Selenium

When dealing with websites that utilize Ajax or javascript to display data, I'm facing a challenge in saving this data using WWW::Selenium. Although my code successfully navigates through the webpage and interacts with the elements, I've encounte ...

What is the process of updating the default version of Firefox using Selenium webdriver in Ruby?

I successfully changed the Firefox version I am using to 33.1 using this code. However, I want to make the current version the default without having to add extra code to each script. path='C:\Program Files (x86)\Mozilla Firefox\firefo ...

The sendKeys command in WebDriver is failing to enter text into the Password field

Currently, I am delving into the world of selenium webdriver automation and have encountered an issue with the sendKeys command not working on Password type fields. After doing some research online, it seems like others are also facing the same problem but ...

Issues with Selenium explicit wait feature in latest version of SafariDriver 2.48.0

Issues with explicit waits in my code are arising specifically when using SafariDriver 2.48.0. The waits function properly in Chrome on both Windows and MAC platforms, but in Safari, upon reaching the wait condition, the driver throws an exception. Upo ...

Is there a way to automate the uploading of captcha images to this solving service using Python?

Currently, I am working on a Python program with the goal of solving captchas on a website. My plan is to integrate 2captcha into the solution. Using Selenium, I have managed to write a Python script that fulfills all required tasks except for solving the ...

Running chromedriver on AWS using Python can be achieved by following a few simple

Currently, I am using selenium for web scraping and the code below functions perfectly when used with a local path. However, I encountered an error message stating "WebDriverException: Message: unknown error: cannot find Chrome binary." I'm uncertain ...

The error message "Unable to establish a connection to security.ubuntu.com:80" keeps popping up while attempting to execute a shell command in Databricks

I have been trying to implement Selenium on an AWS Databricks platform following the guidelines in a recent post. However, every time I execute the code provided, I encounter the same error: Partial Error: Could not connect to security.ubuntu.com:80 Code ...

Tips for using Selenium to download .csv files in Python

Utilizing Selenium to browse through this particular website: https://apps1.eere.energy.gov/sled/#/ I am interested in obtaining data for a city such as Boston: here is my process: from selenium import webdriver from selenium.webdriver.common.keys impor ...

Ensuring Accuracy of Error Messages with Selenium WebDriver

Could use some help with validating error message text in a try-catch block. It seems to be catching every time, looking for advice on the syntax or a better approach to validation. string actualResultText = ""; string expectedResultText = " ...

A guide on incorporating Django Selenium testing into GitHub Actions

Currently working on a Django project, I have a test case that inherits from django.test.LiveSeverTestCase and utilizes Selenium: from django.test import LiveServerTestCase from selenium.webdriver.chrome.webdriver import WebDriver class FrontEndTestCase(L ...

Guide to using Python and Selenium to extract the titles of each search result

I am currently learning Python and attempting to extract search results from python.org using the Selenium library. Here are the steps I want to follow: Open python.org Search for the term "array" (which will display the results) Paste the list of searc ...

When a button is clicked within a partial view, it will redirect to the parent action

I am struggling with implementing an AJAX call using jQuery in a partial view within my application. I have a parent view called 'Parent' where I am using @Html.BeginForm and a submit button to save data. However, whenever I try to make the AJAX ...

Having trouble accessing the website link in the browser

I recently developed a basic automation script in Python using Selenium but encountered an unexpected exception. Here is the code snippet causing the issue: import pandas as pd from pandas import ExcelWriter from selenium import webdriver import seleniu ...

The mouseover functionality is not functioning properly in Selenium with Java and Chrome

I'm attempting to automate the hover action on a specific element, which in this case is a designated office name. When I hover over an office, its information should be displayed. However, when I execute this code: String officeId = findElement(desi ...

Maximizing Efficiency: Distributing Tests Equally Across Nodes with Selenium Grid

I need to run a total of 1000 tests, with each node registered to the hub handling 200 tests. I have 5 nodes connected to the hub. What is the best way to achieve this test distribution? ...

Encountering the Selenium Webdriver HTTP error within an Angular 4 project

ERROR Detected Issue found in: ./node_modules/selenium-webdriver/http/index.js Module not found: Error: Unable to locate 'http' in 'C:\Users\aprajita.singh\Documents\Angular 4\Auto-Trender-Project\node_modules ...

Having trouble finding a webpage element (button) with the ID 'next' using Python and Selenium

I recently delved into Python with Selenium to automate tasks, but I've hit a roadblock. My goal is to create a script that automatically clicks the 'next' button on a webpage. However, I'm facing difficulty in locating the element (but ...

Selenium is having difficulty clicking on a table row, even though it can be done manually

On my webpage, a table is populated dynamically through an API call. Each row in the finalized table is structured as follows: <tr class="ant-table-row ant-table-row-level-0" data-row-key="0"> <td class="">Value1</td> <td class="" ...

Decoding Json data in C# using JSON.NET

I am currently working on a C# application that retrieves the backpack value of players in a game called TF2 using Backpack.tf's API. Here is a snippet of the code: (MAIN CLASS) JsonConvert.DeserializeObject<Json1>(json); (END OF MAIN CLASS) ...