Browser.cs:
public static ChromeDriver GetChromeDriver(string machine)
{
String chromeLocalAppDataPath = GetChromeLocations(machine); //"d:\ChromeTest\Google\Chrome\User Data\Auto\";
var headless = true;
var options = new ChromeOptions();
options.AddArgument("--no-experiments");
options.AddArgument("disable-infobars");
options.AddArgument("--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36");
if (headless)
options.AddArgument("headless");
options.AddArgument("no-sandbox");
options.AddArguments("user-data-dir=" + chromeLocalAppDataPath);
options.BinaryLocation = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";
return new ChromeDriver(options);
}
运行:
var driver = Browser.GetChromeDriver("P1"); // user profile 1
driver.Navigate().GoToUrl("https://google.com/");
基本上,我构建这些小应用程序来调用多个Chrome实例,现在我想知道是否有一种方法可以从另一个应用程序中识别进程,所以如果我想删除Profile 1从Process.GetProcessesByName("chromedriver")启动的指定的铬进程
发布于 2020-07-11 11:40:21
如果您想获得由chromedriver启动的Chrome进程的标识,那么下面是一个解决方案。这个例子在C#中。其他语言(如Java)也有相同的实现,但我只在C#中工作。
Chrome允许您提供您自己定义的命令行参数。因此,您可以使用当前运行的程序的PID ()添加一个名为"scriptpid-“的参数。ChromeDriver将您的参数传递给命令行中的Chrome。然后使用Windows调用从运行中的Chrome命令行检索这个PID .
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。
https://stackoverflow.com/questions/59575170
复制相似问题