use*_*651 6 c# selenium pid webdriver selenium-webdriver
在C#中我启动了一个浏览器进行测试,我想得到PID,以便在我的winforms应用程序中我可以杀死所有剩余的ghost进程
driver = new FirefoxDriver();
Run Code Online (Sandbox Code Playgroud)
我怎样才能获得PID?
小智 13
int _processId = -1;
var cService = ChromeDriverService.CreateDefaultService();
cService.HideCommandPromptWindow = true;
// Optional
var options = new ChromeOptions();
options.AddArgument("--headless");
IWebDriver webdriver = new ChromeDriver(cService, options);
_processId = cService.ProcessId;
Console.Write("Process Id : " + _processId);
webdriver.Navigate().GoToUrl("https://www.google.lk");
webdriver.Close();
webdriver.Quit();
webdriver.Dispose();
Run Code Online (Sandbox Code Playgroud)
看起来更像是一个C#问题,而不是Selenium特有的.
这是一个非常古老的非确定性答案,如果您想尝试这一点,请重新考虑.
我的逻辑是你firefox使用Process.GetProcessesByName方法获取名称的所有进程PID ,然后启动你的FirefoxDriver,然后再次获取进程的PID,比较它们以获得刚启动的PID.在这种情况下,特定驱动程序启动了多少进程并不重要(例如,Chrome启动多个,Firefox只启动一个).
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Firefox;
namespace TestProcess {
[TestClass]
public class UnitTest1 {
[TestMethod]
public void TestMethod1() {
IEnumerable<int> pidsBefore = Process.GetProcessesByName("firefox").Select(p => p.Id);
FirefoxDriver driver = new FirefoxDriver();
IEnumerable<int> pidsAfter = Process.GetProcessesByName("firefox").Select(p => p.Id);
IEnumerable<int> newFirefoxPids = pidsAfter.Except(pidsBefore);
// do some stuff with PID if you want to kill them, do the following
foreach (int pid in newFirefoxPids) {
Process.GetProcessById(pid).Kill();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 6
var g = Guid.NewGuid();
driver.Navigate().GoToUrl("about:blank");
driver.ExecuteScript($"document.title = '{g}'");
var pid = Process.GetProcessesByName("firefox").First(p =>
p.MainWindowTitle.Contains(g.ToString()));
Run Code Online (Sandbox Code Playgroud)
我没有尝试使用 Firefox,但这就是 Chrome 的工作方式:
// creating a driver service
var driverService = ChromeDriverService.CreateDefaultService();
_driver = new ChromeDriver(driverService);
//create list of process id
var driverProcessIds = new List<int> { driverService.ProcessId };
//Get all the childs generated by the driver like conhost, chrome.exe...
var mos = new System.Management.ManagementObjectSearcher($"Select * From Win32_Process Where ParentProcessID={driverService.ProcessId}");
foreach (var mo in mos.Get())
{
var pid = Convert.ToInt32(mo["ProcessID"]);
driverProcessIds.Add(pid);
}
//Kill all
foreach (var id in driverProcessIds)
{
System.Diagnostics.Process.GetProcessById(id).Kill();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10114 次 |
| 最近记录: |