用C#捕获Selenium中的ElementClickInterceptedException异常

e3bfsja2  于 2023-02-19  发布在  C#
关注(0)|答案(1)|浏览(184)

我试图在C#中捕获ElementClickInterceptedException,但似乎我做错了什么,因为在调试时,当我获得异常时,它没有转到catch代码行。奇怪的是,如果测试正常运行,它不会在此时抛出异常,但当它在调试模式下运行时,它会...

我尝试捕获异常,因为Selenium一直抛出它,我不知道该怎么解决它。

gpnt7bae

gpnt7bae1#

看起来我沿着都在捕捉错误的异常。无论如何,我会留下在我遇到TargetInvocationException或ElementClickInterceptedException时为我工作的代码,这样任何面临同样问题的人都可以像我一样解决它:

public bool clickBtn(IWebElement btnElement)
        {
            bool result = false;
            int attempts = 0;
            while (attempts < 10)
            {
                try
                {
                    waitForClickable(btnElement);
                    btnElement.Click();
                    result = true;
                    break;
                }
                catch (TargetInvocationException e)
                {
                }
                catch (StaleElementReferenceException e)
                {
                }
                attempts++;
                Thread.Sleep(2000);
            }
            return result;
        }

我想你可以摆脱第二次接球,它还是会起作用的:)
另外,我保留了“waitForClickable”方法的代码:

internal void waitForClickable(IWebElement button)
        {
            try
            {
                wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementToBeClickable(button));
            }
            catch (NoSuchElementException e)
            {
                throw new NoSuchElementException("It wasn't possible to click the element.\n" + e);
            }
        }

相关问题