侧边栏壁纸
博主头像
怪客のBlog 博主等级

行动起来,活在当下

  • 累计撰写 35 篇文章
  • 累计创建 1 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

C# Selenium初始化ChromeDriver自动下载驱动文件

怪客
2023-01-18 / 0 评论 / 0 点赞 / 200 阅读 / 0 字

代码

        #region 初始化ChromeDriver
        /// <summary>
        /// 初始化ChromeDriver
        /// </summary>
        public static void InitChromeDriver()
        {
            try
            {
                bool needDownload = true;
                LogInfo.Info("开始下载Chrome驱动文件...");
                string version = string.Empty;
                string fileName = string.Empty;
                if (OSInfo == OSPlatform.Windows)
                {
                    version = ConfigHelper.GetConfig("WindowsChromeVersion");
#pragma warning disable CA1416 // 验证平台兼容性
                    string chromePath = Microsoft.Win32.Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\chrome.exe", "Path", null)?.ToString()??"";
#pragma warning restore CA1416 // 验证平台兼容性
                    if (string.IsNullOrWhiteSpace(chromePath))
                    {
                        throw new Exception("请先安装谷歌浏览器!");
                    }
                    string nowversion = FileVersionInfo.GetVersionInfo(chromePath + @"\chrome.exe")?.FileVersion?? "";
                    if (version == nowversion)
                    {
                        if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "chromedriver.exe"))
                        {
                            needDownload = false;
                        }
                    }
                    version = nowversion;
                }
                else if (OSInfo == OSPlatform.Linux)
                {
                    version = ConfigHelper.GetConfig("LinuxChromeVersion");
                    string result = WorkerHelper.RunLinuxCmd("google-chrome --version");
                    if (!result.StartsWith("Google Chrome "))
                    {
                        throw new Exception("请先安装谷歌浏览器!");
                    }
                    string nowversion = result.Replace("Google Chrome ", "").Trim();
                    if (version == nowversion)
                    {
                        if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + "chromedriver"))
                        {
                            needDownload = false;
                        }
                    }
                    version = nowversion;
                }
                else
                {
                    throw new Exception("目前仅支持Windows和Linux!");
                }
                if (!needDownload)
                {
                    LogInfo.Info("Chrome驱动文件已是最新!");

                    return;
                }
                LogInfo.Info($"当前安装谷歌浏览器版本【{version}】");
                string file = $"chromedriver_{(OSInfo == OSPlatform.Windows ? "win32" : "linux64")}.zip";
                string xml = WorkerHelper.GetHtml("http://chromedriver.storage.googleapis.com", "utf-8");
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(xml);
                dynamic? data = JsonConvert.DeserializeObject<dynamic>(JsonConvert.SerializeXmlNode(xmldoc));
                List<dynamic>? allVersion = data?.ListBucketResult.Contents.ToObject<List<dynamic>>();
                if (allVersion != null && allVersion.Count > 0)
                {
                    allVersion = allVersion.Where(t => t.Key.ToString().StartsWith(version?.Substring(0, version.LastIndexOf("."))) && t.Key.ToString().Contains(file)).ToList();
                    if (!allVersion.Select(t => t.Key).Contains(version))
                    {
                        string key = allVersion.OrderByDescending(t => Convert.ToDateTime(t.LastModified)).First().Key;
                        version = key.Substring(0, key.IndexOf("/"));

                    }
                }
                string download_url = $"http://chromedriver.storage.googleapis.com/{version}/{file}";

                WorkerHelper.DownloadFileAsync(download_url, AppDomain.CurrentDomain.BaseDirectory + file, (total, downloaded, progress) =>
                {
                    LogInfo.Info($"总大小【{total}】,已下载【{downloaded}】,进度【{progress}%】");
                    if (total == downloaded && progress == 100)
                    {
                        try
                        {
                            bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
                            bool isLinux = RuntimeInformation.IsOSPlatform(OSPlatform.Linux);
                            LogInfo.Info("下载完成,开始解压...");
                            ZipFile.ExtractToDirectory(AppDomain.CurrentDomain.BaseDirectory + $"chromedriver_{(isWindows ? "win32" : "linux64")}.zip", AppDomain.CurrentDomain.BaseDirectory, true);
                            LogInfo.Info("解压完成!");
                            if (isLinux)
                            {
                                LogInfo.Info("开始文件授权...");
                                WorkerHelper.chmod("chromedriver", chodType._0777);
                                LogInfo.Info("chromedriver文件授权完成!");
                            }
                        }
                        catch (Exception ex)
                        {
                            LogInfo.Error("解压ChromeDriver压缩文件失败," + ex.Message);
                        }
                    }
                }).Wait();
                ConfigHelper.SetConfig(OSInfo == OSPlatform.Linux ? "LinuxChromeVersion" : "WindowsChromeVersion", version);
            }
            catch (Exception ex)
            {
                LogInfo.Error($"初始化ChromeDriver错误:{ex.Message}!");
            }
        }
        #endregion
0

评论区