c#爬蟲-從內存中釋放Selenium chromedriver.exe終極殺

背景

之前在做爬蟲的時候,遇到內存釋放不掉的問題,從內存中釋放Selenium chromedriver.exe。後面我使用以下方法:

public override void DoJob(IJobExecutionConxt context, ILifetimeScope scope, string[] args)
        {
            Console.WriteLine(nameof(LoginReptiles1688Job) + " 開始-------------------");
            ChromeOptions options = null;
            IWebDriver driver = null;
            try
            {
            。。。。。。。。。。。。。。。。。。。。。。。
                  }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                driver?.Close(); // Close the chrome window
                driver?.Quit(); // Close the console app that was used to kick off the chrome window
                driver?.Dispose(); // Close the chromedriver.exe

                driver = null;
                options = null;
                detailtry = 0;
                shoptry = 0;
                Console.WriteLine(nameof(LoginReptiles1688Job) + " 結束-------------------");
            }
        }

這不,還真降下來了;但是,沒等幾天服務器又報警了,還是老問題,後面搗鼓了半天,還是沒有解決問題。

問題窺探

其實問題的根本原因是Selenium chromedriver.exe沒法正常關閉,雖然嘗試了很多方法,但是始終沒法測底解決;後面靈機一閃,何不來個徹底點的,使用kill把整個chromedriver.exe線程幹掉,這不就徹底了;說幹就幹。

主要代碼

 #region 異常  退出chromedriver

        [DllImport("user32.dll", EntryPoint = "FindWindow")]
        private extern static IntPtr FindWindow(string lpClassName, string lpWindowName);

        [DllImport("user32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);

        public const int SW_HIDE = 0;
        public const int SW_SHOW = 5;

        [DllImport("user32.dll", EntryPoint = "ShowWindow")]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

        /// <summary>
        /// 獲取窗口句柄
        /// </summary>
        /// <returns></returns>
        public IntPtr GetWindowHandle()
        {
            string name = (Environment.CurrentDirectory + "\\chromedriver.exe");
            IntPtr hwd = FindWindow(null, name);
            return hwd;
        }

        /// <summary>
        /// 關閉chromedriver窗口
        /// </summary>
        public void CloseWindow()
        {
            try
            {
                IntPtr hwd = GetWindowHandle();
                SendMessage(hwd, 0x10, 0, 0);
            }
            catch { }
        }

        /// <summary>
        /// 退出chromedriver
        /// </summary>
        /// <param name="driver"></param>
        public void CloseChromeDriver(IWebDriver driver)
        {
            try
            {
                driver.Quit();
                driver.Dispose();
            }
            catch { }
            CloseWindow();
        }

        #endregion 異常  退出chromedriver

總結

1、果然夠徹底的,chromedriver.exe每次都正常關閉了,內存佔用也正常。

2、事有兩面性,有時候反方向來解決問題未嘗不是一個好的辦法。

3、使用這種方式,等於kill掉整個進程,所以不適合多個線程操作,否則會出 現中斷的情況。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章