Home > Mobile >  During unsuccessful selenium ChromeDriver creation chromedriver.exe is not being disposed
During unsuccessful selenium ChromeDriver creation chromedriver.exe is not being disposed

Time:08-26

I can create ChromeDriver with selenium just fine. Example

var driverOptions = new ChromeOptions();
driverOptions.AddArgument("headless");

var chromeDriverPath = Path.Combine(AppContext.BaseDirectory, "ChromeDriver");
using var driver = new ChromeDriver(chromeDriverPath, driverOptions);

Problem is when something goes wrong and last line throws an error. I can simulate this by providing bad binary path to chrome. For example:

driverOptions.BinaryLocation = "a";

Then I get an error "no chrome binary at a at..." Which is fine, it's to be expected.

But what I do not like is how chromedriver.exe remains as running process. Every failed execution new chromedriver.exe process is being created.

Is there more elegant way of doing this besides:

try
{
        var driverOptions = new ChromeOptions();
        driverOptions.AddArgument("headlessY");
        driverOptions.BinaryLocation = "a";

        var chromeDriverPath = Path.Combine(AppContext.BaseDirectory, "ChromeDriver");
        using var driver = new ChromeDriver(chromeDriverPath, driverOptions);
        ...
}
catch(Exception)
{
        //List all processed and kill every process with a name of chromedriver.exe
}

CodePudding user response:

The ChromeDriverService class has a ProcessId property, which is the exact process Id of ChromeDriver.exe. You can use this to explicitly kill that process after a failed driver initialization.

var chromeDriverPath = Path.Combine(AppContext.BaseDirectory, "ChromeDriver");
var service = ChromeDriverService.CreateDefaultService(chromeDriverPath);

try
{
    var driverOptions = new ChromeOptions();
    driverOptions.AddArgument("headlessY");
    driverOptions.BinaryLocation = "a";

    using var driver = new ChromeDriver(service, driverOptions);
    ...
}
catch(Exception)
{
    if (service.ProcessId != default)
    {
        var process = Process.GetProcessById(service.ProcessId);

        process.Kill();
    }
}

This allows you to clean up "zombie" driver instances. This basic process should work for Edge and Firefox as well. Otherwise you are stuck with opening a command shell and executing taskkill /f /im chromedriver.exe.

  • Related