0

我正在使用 C#/Selenium 3 和 Microsoft Chromium Edge Webdriver 来抓取网页,然后将数据传送到另一个应用程序。我需要检查用户是否关闭了网络浏览器。有没有一种快速的方法来做到这一点?我想出了下面的代码,但问题是如果 Web 浏览器关闭,那么 _webDriver.CurrentWindowHandle 需要 4 秒或更长时间才能引发异常。

public bool IsOpen
{
    get
    {
        if (!this._isDisposed)
        {
            try
            {
                _ = this._webDriver.CurrentWindowHandle;
                return true;
            }
            catch
            {
                // ignore.
            }
        }

        return false;
    }
}
4

2 回答 2

0

抛出异常需要几秒钟,因为当浏览器关闭时,驱动程序仍然会重试连接到浏览器。它无法判断浏览器是手动关闭还是自动关闭。

我需要检查用户是否关闭了网络浏览器

自动化浏览器测试不应被人工干预中断。这与所有最佳实践背道而驰。如果您手动关闭浏览器,WebDriver 将抛出WebDriverException。因此,您还可以使用try-catch方法 onWebDriverException检查浏览器是否可访问。但是抛出异常也需要几秒钟的时间,原因与上述相同。

如果要防止用户手动关闭浏览器,可以在无头模式下使用 Edge,如下所示:

edgeOptions.AddArguments("--headless");
于 2021-05-19T07:18:06.830 回答
0

最后我想出了以下解决方案:我使用扩展方法(如下所示)来获取 Web 浏览器的 .Net Process 对象。要检查浏览器是否仍然打开,我只需检查属性 process.HasExited。如果这是真的,那么用户已经关闭了浏览器。此方法不调用 Selenium,因此即使浏览器关闭,结果也几乎是即时的。

/// <summary>
/// Get the Web Drivers Browser process.
/// </summary>
/// <param name="webDriver">Instance of <see cref="IWebDriver"/>.</param>
/// <returns>The <see cref="Process"/> object for the Web Browser.</returns>
public static Process GetWebBrowserProcess(this IWebDriver webDriver)
{
    // store the old browser window title and give it a unique title.
    string oldTitle = webDriver.Title;
    string newTitle = $"{Guid.NewGuid():n}";

    IJavaScriptExecutor js = (IJavaScriptExecutor)webDriver;
    js.ExecuteScript($"document.title = '{newTitle}'");

    // find the process that contains the unique title.
    Process process = Process.GetProcesses().First(p => p.MainWindowTitle.Contains(newTitle));

    // reset the browser window title.
    js.ExecuteScript($"document.title = '{oldTitle}'");
    return process;
}
于 2021-05-19T13:02:48.933 回答