What is preventing me from having two consecutive waits in a row?

So I've been having trouble with clicking a checkbox using the correct xpath. It only seems to work when the checkbox is visible after scrolling down the page. I came across some javascript code called scrollviewandclick that is used in conjunction with selenium. So, whenever I want to click something that is out of view, I simply use:

objCommon.ScrollInToViewAndClick(driver.FindElement(By.Xpath("YOUR Locator")));

I have also tried clicking by moving my mouse to the checkbox with the following code:

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(driver.FindElement(By.Xpath("YOUR Locator"))).Click();

However, I am struggling to combine the scrollviewandclick method with this click action as it does not allow me to put two waits together. Can anyone provide insight into where I might be going wrong?

Below is the code for the scrollviewandclick method:

public void ScrollInToViewAndClick(IWebElement element)
        {
            IJavaScriptExecutor executor = (IJavaScriptExecutor)driver;
            executor.ExecuteScript("arguments[0].scrollIntoView(true);", element);

            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
            var elementList = new List<IWebElement>
            {
                element
            };

            var readonlyCollection = new ReadOnlyCollection<IWebElement>(elementList);
            wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.VisibilityOfAllElementsLocatedBy(readonlyCollection));
            wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(element)).Click();

        }

Answer №1

Instead of calling .Click() within Wait.Until(), it is recommended to use element.Click() following the second wait for better results.

Answer №2

Performing two consecutive waits should not present any issues, and it's unclear what kind of error you might be encountering. Given that you appear to have limited experience with Selenium, allow me to provide some guidance and recommendations:

  1. Are you converting a single WebElement into a collection for a specific purpose? It seems unnecessary if your goal is to utilize

    VisibilityOfAllElementsLocatedBy()
    . Instead, consider using the singular version of this wait method, which is ElementIsVisible().

  2. Waiting for an element to be visible before waiting for it to be clickable isn't necessary. An element must be visible in order to be clickable, so waiting for clickability alone is sufficient.

  3. If you attempt to scroll to an element before it becomes visible, an error will occur. Therefore, wait until the element is clickable (visible), then scroll to it, and finally click on it.

With these points in mind, I have revised your code as shown below.

public void ScrollInToViewAndClick(IWebElement element)
{
    new WebDriverWait(driver, TimeSpan.FromSeconds(20)).Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(element));
    ((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].scrollIntoView(true);", element);
    element.Click();
}

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

Is there a way to incorporate an array into an array of arrays with jQuery?

I am working with an array shown below: var cString = [ ['1','Techdirt','www.techdirt.com'], ['2','Slashdot','slashdot.org'], ['3','Wired&apos ...

How can Socket.io prevent other pages from receiving all messages?

I apologize for the confusing title, but I am in need of some assistance in clarifying my question. The situation is as follows: I have a website page that is receiving messages from a node server. socket.on('item finished', function(data){ ...

How can I simulate pressing the ENTER key in Selenium without selecting any element?

Having trouble using the firefox selenium plugin and sending the enter key after pasting text? The ENTER key press should not interact with any other element on the page, just a simple 'dumb' ENTER key press. error [error] Element name=code not ...

Is there a way to adjust the time font size according to the dimensions of the time picker?

HTML and CSS .pickthetime { height: calc(var(--vh, 1vh) * 3); width: calc(var(--vw, 1vw) * 25); align-content: center; // center looks better, also tried left to stop it from breaking a new line on Safari on iOS font-weight: 300; } <input cla ...

What is causing Puppeteer to not wait?

It's my understanding that in the code await Promise.all(...), the sequence of events should be: First console.log is printed 9-second delay occurs Last console.log is printed How can I adjust the timing of the 3rd print statement to be displayed af ...

Error in Node and Express: Unable to access route

Currently, I am in the process of developing an Express application and running into some obstacles with routing. While my '/' route is functioning perfectly fine, other routes are not working as expected. Despite researching similar questions fr ...

Utilizing Angular's ng-Grid with Promises

My current setup involves fetching a JSON file through a service to serve as the data source for my grid. The service successfully fetches the data, and the grid renders its basic layout correctly. However, there seems to be an issue with populating the gr ...

Change the term to its corresponding translation

I have developed an Ionic Multilingual App that includes a select feature. Within this select, choosing a specific option disables certain page elements. However, I am facing an issue where one of the elements needs to change its text based on the selected ...

How to Display Prices in Euros Currency with Angular Filter

Can someone help me figure out how to display a price in euros without any fractions and with a dot every 3 digits? For example, I want the price 12350.30 to be shown as 12.350 €. I attempted to use the currency filter but it only worked for USD. Then ...

Extracting HTML element from PHP string and placing it in a different page

In a PHP string, there is an HTML structure including a table within it: <html> <head> <!-- not much going on here --> </head> <body> <table border="0" align="center" cellpadding="0" cellspacing="10 ...

Convert the text inside a span element into a key-value object in JavaScript

How can I extract and save the text from a span element as key value pairs within a div? <div class="data-diff-span__composite-list-item__18c5zip data-diff-core__highlight-area__19c0zip"> <div class="data-diff-basic__class-row__4n ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

JQuery UI Autocomplete: Results, Ctrl + A and Delete

I am currently designing a form that allows users to add members to a project. Only members with existing profiles in the system can be added. The form includes an input field for the member's name and a select box for their position, which is initial ...

Guide to setting up the redux-form with initial values pulled from the store

I am looking to preload a Redux Form with values obtained from the store. Currently, I can populate the redux form with data directly from the reducer. However, when submitting the form, it only accepts data for clickable elements to generate the payload. ...

Exclude OData entity collections from the $metadata endpoint

In my .NET 5 web api, I have developed an OData service that exposes entity types and sets for various parts of the system. This includes a public section for general data export and a "private" section reserved for internal applications. However, some of ...

Enhancing code branch coverage using Istanbul

The code snippet provided has a branch coverage of only 50% (refer to the coverage report below). I am unsure how to enhance this as there are no if statements present. I suspect that Istanbul must utilize some form of measurement that I have yet to grasp ...

Can I issue multiple SADD or ZADD commands in a single .sadd/.zadd call using ioredis?

I'm currently experimenting with ioredis for caching and indexing a substantial volume of data. However, my searches haven't yet yielded information on whether it supports performing multiple SADDs in one call. Can this be done, and if so, are t ...

Performing a sequential click on individual row elements within a <table><tr> loop using Selenium and Python

I need help with querying an HTML table. Here is my code: browser.get("url.html") # Wait for page to load # Implement EC.visibility_of_element_located here table_rows = browser.find_elements_by_xpath("//*[@id='table_id']/tbody/tr ...

Looking for assistance grasping the concept of using a for loop in MongoDB's aggregate method

This code snippet is designed to maintain the order of an array (var list) when utilizing mongoDb's $in clause effectively. Although, I must admit that the logic behind it is not entirely clear to me. I can see that it's iterating in reverse to ...

Implementing Exclusions in TimeSpan using C#

Is there a way in .NET to find shortcuts or mechanisms for organizing my 'Diary' which contains events or 'Appointments'? For example, if I have the following schedule: 9AM - 5PM 10AM - 12PM - Appointment 1 1PM - 1:30PM - Appointme ...