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

标签 java c# 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");
    }
}

最佳答案

在 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;
}

在 dotnet 绑定(bind)中,ExpectedConditions消费时不需要WebDriverWait.Until<T> 。您只需发送 Func<IWebDriver, T>适合你的情况。

还值得注意的是,如果 Until未能满足条件,它将在抛出之前检查配置的忽略异常类型列表。 -Details on configuring these

有关使用 dotnet 绑定(bind)获取 cookie 的更多详细信息,请查看 ICookieJar界面。

有关使用 dotnet 绑定(bind)进行自定义等待的其他信息通常可以在 here 中找到。 .

希望这有帮助!

关于java - 如何在 C# Selenium WebDriver 中等待登录 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42341417/

相关文章:

java - Swing : Can children exceed the bounds of their parent?

c# - 生成的小行星向生成时发现的玩家位置移动,但不会更远

java - 将Keys发送到您无法检查的文本框(使用Java)

java - 无状态 session bean 中的同步方法在 glassfish 中无法按预期工作

hbase - Java API 错误 : org. apahe.hadoop.hbase 不存在

java - 连接改变结果类型

c# - 如何在 C# 中使用 ILNumerics ILMath 计算矩阵的逆?

c# - Windows Phone 7 中具有特定编码的 UrlEncode?

java - 无法使用带有 Selenium Webdriver 的 AutoIT 将图像保存在所需位置/文件夹

python - 如何使用 selenium python 打开新窗口