[Robot]Selenium刪除重複存在的瀏覽器個體

  • 313
  • 0
  • 2018-04-24

[Robot]Selenium刪除重複存在的瀏覽器個體

使用Selenium自動化執行瀏覽器的時候,難免會碰到異常,結果就沒有正常關閉,
導致Chrome, PhantomJS, Firefox沒有正常關閉,這時候就要去刪除他,不然電腦的記憶體很快就爆囉....:
 

private static void KillUncontrollerBrowser()
{
	string str = "chrome;firefox;phantomjs";
	foreach (var item in str.Split(';'))
	{
		KillUncontrollerProcess(item);
	}
}
/// <summary>
/// kill有 ParentID 的process
/// </summary>
/// <param name="ProcessName">傳入要檢查的exe名稱(ex: firefox,chrome,phantomjs)</param>
private static void KillUncontrollerProcess(string ProcessName)
{

	Process[] ProcList = Process.GetProcessesByName(ProcessName);


	foreach (Process proc in ProcList)
	{
		try
		{
			ManagementObject managementObject = new ManagementObject(string.Format("win32_process.handle='{0}'", proc.Id));
			managementObject.Get();
			int parentId = Convert.ToInt32(managementObject["ParentProcessId"]);

			try
			{
				if (parentId == 0)
				{
					continue;
				}
				Process parentProc = Process.GetProcessById(parentId);
				if (parentProc.ProcessName == "chromedriver")
				{
					//先刪除此process的parent process                            
					parentProc.Kill();
					//再刪除自己
					proc.Kill();
				}


			}
			catch
			{


				continue;
			}
		}
		catch
		{

			continue;
		}


	}

	//難免會有之前執行沒刪除乾淨的chromedriver.exe
	foreach (var process in Process.GetProcessesByName("chromedriver"))
	{
		try
		{
			process.Kill();
		}
		catch
		{
			SpinWait.SpinUntil(() => false, 5000);
			return;
		}

	}


}

大概是這樣………

本篇跟下面這篇有互相協助的功用:
[robot]每次執行完畢需關閉Selenium節省資源