【发布时间】:2017-12-13 09:31:07
【问题描述】:
有人在 selenium c# 中有任何 scipt, 而不是这一行: IWebDriver driver = new ChromeDriver();
在不打开新的 chrome 窗口的情况下初始化驱动程序, 我的意思是,在第二次运行中,我将处理我在之前的 selenium 运行中打开的 chrome。
谢谢
【问题讨论】:
标签: c# selenium-webdriver
有人在 selenium c# 中有任何 scipt, 而不是这一行: IWebDriver driver = new ChromeDriver();
在不打开新的 chrome 窗口的情况下初始化驱动程序, 我的意思是,在第二次运行中,我将处理我在之前的 selenium 运行中打开的 chrome。
谢谢
【问题讨论】:
标签: c# selenium-webdriver
您可以致电x.Driver 获取相同的驱动程序实例。
private static IWebDriver driver;
public IWebDriver Driver {
get {
if (driver == null)
{
driver = new ChromeDriver();
}
return driver;
}
}
【讨论】:
这是我使用的方法。 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。
【讨论】: