问题
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
回答1:
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.
回答2:
You need to consider a couple of things.
- To invoke
MoveToElement()
, ExpectedConditions asElementToBeClickable()
is overkill. Instead you can do away withElementIsVisible()
. - While invoking
Click()
as per best practices you need to invoke WebDriverWait inconjunction with ExpectedConditions asElementToBeClickable()
. So effectively, your code block will be:
Actions action = new Actions(driver); action.MoveToElement(new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementIsVisible(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")))).Perform(); new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(ExpectedConditions.ElementToBeClickable(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"))).Click();
来源:https://stackoverflow.com/questions/60457995/selenium-wait-for-outofbound-element-c-sharp