Search code examples
c#seleniumactionindexoutofboundsexceptionwebdriverwait

Selenium - Wait for OutOfBound element C#


I use Selenium C# binding and I want to click over the addToCart button.

First, I'm waiting the button appears on the page with ExpectedConditions.ToBeClickable.

Then, I need to scroll down the page to be able to click over the button. I used the Selenium.Interactions class but it work as well with js executor.

private By addToCartBy = By.XPath("/html/body/div[2]/div/div/div[1]/div/div[3]/div[2]/div/section[1]/div[2]/aside/div/div[2]/div/div[2]/div/button");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5));
IWebElement addToCart = wait.Until(ExpectedConditions.ElementToBeClickable(addToCartBy));
Actions action = new Actions(driver);
action.MoveToElement(addToCart);
action.Perform();
addToCart.Click();

When I perform this test with Chrome driver, the page loads and the navigator scroll down to the element addToCart and click it but I'm unable to get the button working properly.

When I use Firefox driver, it raise this exception: OpenQA.Selenium.WebDriverException : '(1435, 998) is out of bounds of viewport width (1920) and height (966)'and I'm unable to click over the button

Most of the time, the click will be performed but no action will follow from this. If I want the button to work properly (go the the cart), I need to put a System.Threading.Thread.Sleep(2000) to be effective or a Console.ReadLine(). Even if I disable the automation click and I do it manually, the button don't always proceed.

How can I make sure my element addToCart is displayed after I moved to Element? in a way to click it when he's ready.

Thank you, Eelke Johnson


Solution

  • For some of the scenarios, you can use not

    IWebElement.Click();

    but

    IWebElement.SendKeys(Keys.Enter);

    I had some scenarios, where just Click() didn't work for me.Maybe this will help in your situation.