【问题标题】:get handle to opened chrome window in selenium获取在 selenium 中打开的 chrome 窗口的句柄
【发布时间】:2017-12-13 09:31:07
【问题描述】:

有人在 selenium c# 中有任何 scipt, 而不是这一行: IWebDriver driver = new ChromeDriver();

在不打开新的 chrome 窗口的情况下初始化驱动程序, 我的意思是,在第二次运行中,我将处理我在之前的 selenium 运行中打开的 chrome。

谢谢

【问题讨论】:

    标签: c# selenium-webdriver


    【解决方案1】:

    您可以致电x.Driver 获取相同的驱动程序实例。

        private static IWebDriver driver;
        public IWebDriver Driver {
            get {
                if (driver == null)
                {
                    driver = new ChromeDriver();
                }
                return driver;
            }
        }
    

    【讨论】:

    • 它对我没有帮助,因为如果我停止运行,我会失去驱动程序的参考。并在追赶中;总是驱动程序将为空。
    【解决方案2】:

    这是我使用的方法。 Chrome 允许您提供自己的用户定义的命令行参数。因此,您可以使用当前正在运行的程序的 PID(Windows 进程 ID)添加一个名为“scriptpid-”的参数。 ChromeDriver 在命令行中将您的参数传递给 Chrome。然后使用 Windows WMI 调用从正在运行的 Chrome 的命令行中检索此 PID ...

    using System.Management;
    
    public static IntPtr CurrentBrowserHwnd = IntPtr.Zero;
    public static int CurrentBrowserPID = -1;
            
    ChromeOptions options = new ChromeOptions();
    options.AddArgument("scriptpid-" + System.Diagnostics.Process.GetCurrentProcess().Id);
    IWebDriver driver = new ChromeDriver(options);
    
    // Get the PID and HWND details for a chrome browser
    
    System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName("chrome");
    for (int p = 0; p < processes.Length; p++)
    {
        ManagementObjectSearcher commandLineSearcher = new ManagementObjectSearcher("SELECT CommandLine FROM Win32_Process WHERE ProcessId = " + processes[p].Id);
        String commandLine = "";
        foreach (ManagementObject commandLineObject in commandLineSearcher.Get())
        {
            commandLine += (String)commandLineObject["CommandLine"];
        }
    
        String script_pid_str = (new Regex("--scriptpid-(.+?) ")).Match(commandLine).Groups[1].Value;
    
        if (!script_pid_str.Equals("") && Convert.ToInt32(script_pid_str).Equals(System.Diagnostics.Process.GetCurrentProcess().Id))
        {
            CurrentBrowserPID = processes[p].Id;
            CurrentBrowserHwnd = processes[p].MainWindowHandle;
            break;
        }
    }
    

    CurrentBrowserHwnd 应包含您的 Chrome 窗口的 HWND。

    CurrentBrowserPID 应包含您的 Chrome 窗口的进程 ID。

    【讨论】:

    • 谢谢@Tal 我已经用“使用 System.Management;”更新了答案
    • 感谢您的修复,但仍未找到 ManagementObjectSearcher..
    猜你喜欢
    • 1970-01-01
    • 2015-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多