如何在 C# Selenium WebDriver 中等待登录 cookie?

Mr *_*ull 3 c# java selenium-webdriver

我之前只使用过 Java,但需要在 C# 中设置一些测试。

在登录测试中,我喜欢有一个等待方法来等待设置登录 cookie。

在 Java 中我可以做类似的事情,但无法在 C# 中创建相同的内容,任何人都可以帮我将此代码转换为 C# 吗?

    public void getTokenCookie(){
    try {
        wait.until(
                new ExpectedCondition<Cookie>() {
                    @Override
                    public Cookie apply(WebDriver webDriver) {
                        Cookie tokenCookie = driver.manage().getCookieNamed("nameOfCookie");
                        if (tokenCookie != null) {
                            System.out.println("\nToken Cookie added: " + tokenCookie);
                            return tokenCookie;
                        } else {
                            System.out.println("waiting for cookie..");
                            return null;
                        }
                    }
                }
        );

    } catch (Exception e){
        System.out.println(e.getMessage());
        fail("Failed to login, no cookie set");
    }
}
Run Code Online (Sandbox Code Playgroud)

Jor*_*dan 5

在 C# 中,我相信上面的代码看起来像这样:

public Cookie GetTokenCookie()
{
    var webDriver = new ChromeDriver(); //or any IWebDriver

    var wait = new WebDriverWait(webDriver, TimeSpan.FromSeconds(10));

    Cookie cookie = default(Cookie);

    try
    {
        cookie = wait.Until(driver =>
        {
            Cookie tokenCookie = driver.Manage().Cookies.GetCookieNamed("nameOfCookie");
            if (tokenCookie != null)
            {
                Console.WriteLine("\nToken Cookie added: " + tokenCookie);
                return tokenCookie;
            }
            else
            {
                Console.WriteLine("waiting for cookie...");
                return null;
            }
        });
    }
    catch (Exception e)
    {
        Console.WriteLine($"{e.Message}");
    }

    return cookie;
}
Run Code Online (Sandbox Code Playgroud)

在 dotnet 绑定中,ExpectedConditions使用时不需要WebDriverWait.Until<T>。您可以根据您的情况发送一份Func<IWebDriver, T>

还值得注意的是,如果Until不满足条件,它将在抛出之前检查配置的忽略异常类型列表。-有关配置这些的详细信息

有关使用 dotnet 绑定获取 cookie 的更多详细信息,请查看ICookieJar接口。

一般而言,有关使用 dotnet 绑定进行自定义等待的其他信息可以在此处找到。

希望这可以帮助!