메뉴 건너뛰기


 

원래 https://github.com/Hyo-Seong/ChromeDriverUpdater

저기에 올라와 있던 것을 주워다 쓰면서 날먹을 하고 싶었는데 뭔가 좀 바뀌어서 404 에러나면서 잘 안되더라.

그래서 소스 보고 뜯어서 되게 고쳐두었다.

 

 

ChromeDriverUpdator cdu = new ChromeDriverUpdator();
//cdu.LogEventAssign(LogAppend);
cdu.UpdateStart(Directory.GetCurrentDirectory() + @"\chromedriver.exe");

 

대충 이렇게 하면 돌아간다.

코드 간소화하기 귀찮아서 그냥 대충 막 고쳐놓고는 줄창 써먹을 예정

 

 

 

 

 

 

namespace JprCeleniumChromeDriverUpdater {

    public class PlatformUrl {
        public string platform;
        public string url;
    }

    public class GoodVersions {
        public string version;
        public string revision;
        public Dictionary<string, PlatformUrl[]> downloads;
    }

    public class GoodVersionJson {
        public string timestamp;
        public GoodVersions[] versions;
    }

    public class ChromeDriverUpdator {

        private GoodVersionJson m_versionInfo;

        private Action<string> m_logAction;
        private const string URL_JSON_GOODVERTION = "https://googlechromelabs.github.io/chrome-for-testing/known-good-versions-with-downloads.json";


        public void LogEventAssign(Action<string> action) {
            m_logAction += action;
        }

        private void LogWrite(string _str) {
            m_logAction?.Invoke(_str);
        }

        public void UpdateStart(string chromeDriverFullPath) {
            if (string.IsNullOrEmpty(chromeDriverFullPath)) {
                throw new ArgumentNullException(nameof(chromeDriverFullPath));
            }

            chromeDriverFullPath = Path.GetFullPath(chromeDriverFullPath);
            LogWrite(chromeDriverFullPath);

            if (!File.Exists(chromeDriverFullPath)) {
                throw new FileNotFoundException();
            }

            Version chromeDriverVersion = GetChromeDriverVersion(chromeDriverFullPath);
            Version chromeVersion = GetChromeVersion();

            LogWrite($"크롬 버전: {chromeVersion}\n크롬 드라이버 버전: {chromeDriverVersion}");
            if (UpdateNecessary(chromeDriverVersion, chromeVersion)) {
                LogWrite($"크롬 드라이버 버전을 업데이트합니다...");
                ShutdownChromeDriver(chromeDriverFullPath);

                using (WebClient client = new WebClient()) {
                    string jsonContent = client.DownloadString(URL_JSON_GOODVERTION);
                    m_versionInfo = JsonConvert.DeserializeObject<GoodVersionJson>(jsonContent);
                }

                UpdateChromeDriver(chromeDriverFullPath, chromeVersion);
                Version newChromeDriverVersion = GetChromeDriverVersion(chromeDriverFullPath);
            } else {
                LogWrite($"크롬 드라이버 버전을 업데이트하지 않습니다.");
            }

        }

        public class ProcessExecuter {
            public string Run(string fileName, string arguments) {
                Process process = new Process();

                process.StartInfo = GetProcessStartInfoForHiddenWindow(fileName, arguments);
                process.Start();

                string output = process.StandardOutput.ReadToEnd();

                process.WaitForExit();

                return output;
            }

            private ProcessStartInfo GetProcessStartInfoForHiddenWindow(string fileName, string arguments) {
                ProcessStartInfo processStartInfo = new ProcessStartInfo();

                processStartInfo.UseShellExecute = false;
                processStartInfo.RedirectStandardOutput = true;
                processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                processStartInfo.CreateNoWindow = true;

                processStartInfo.FileName = fileName;
                processStartInfo.Arguments = arguments;

                return processStartInfo;
            }
        }

        internal Version GetChromeDriverVersion(string chromeDriverPath) {
            string output = new ProcessExecuter().Run($"{chromeDriverPath}", "-v");
            string versionStr = output.Split(' ')[1];
            Version version = new Version(versionStr);

            return version;
        }

        public string ChromeDriverName => "chromedriver.exe";
        public string ChromeDriverZipFileName => "chromedriver_win64.zip";
        public Version GetChromeVersion() {
            using (RegistryKey key = Registry.CurrentUser.OpenSubKey("Software\\Google\\Chrome\\BLBeacon")) {
                if (key != null) {
                    object versionObject = key.GetValue("version");

                    if (versionObject != null) {
                        Version version = new Version(versionObject as String);

                        return version;
                    }
                }
            }

            return null;
        }

        internal bool UpdateNecessary(Version chromeVersion, Version driverVersion) {
            //revision은 하지마
            if (chromeVersion.Major == driverVersion.Major &&
                   chromeVersion.Minor == driverVersion.Minor &&
                   chromeVersion.Build == driverVersion.Build) {
                return false;
            } else return true;
        }

        internal void ShutdownChromeDriver(string chromeDriverFullPath) {
            var processes = Process.GetProcesses();

            foreach (Process process in processes) {
                // find exact path
                if (process.MainWindowTitle == chromeDriverFullPath) {
                    process.Kill();
                }
            }
        }

        private void UpdateChromeDriver(string existChromeDriverFullPath, Version chromeVersion) {
            string zipFileDownloadPath = DownloadChromeDriverZipFile(chromeVersion);

            string newChromeDriverFullPath = GetNewChromeDriverFromZipFile(zipFileDownloadPath);

            if (newChromeDriverFullPath != null) {
                File.Copy(newChromeDriverFullPath, existChromeDriverFullPath, true);

                File.Delete(newChromeDriverFullPath);
                LogWrite("새로운 크롬 드라이버 버전 설치 완료");
            }

        }

        internal string DownloadChromeDriverZipFile(Version chromeVersion) {
            int bestVersionIndex = -1;
            Version bestNewVersion = null;
            for (int i = 0; i < m_versionInfo.versions.Length; i++) {
                GoodVersions sample = m_versionInfo.versions[i];
                if (Version.TryParse(sample.version, out Version parsedVersion)) {
                    if (((bestNewVersion == null) || (bestNewVersion < parsedVersion))
                        && (chromeVersion.Major == parsedVersion.Major)
                        && (chromeVersion.Minor == parsedVersion.Minor)
                        && (chromeVersion.Build == parsedVersion.Build)) {
                        bestVersionIndex = i;
                        bestNewVersion = parsedVersion;
                    }
                } else {
                    continue;
                }

            }

            string downloadUrl = string.Empty;
            if (bestNewVersion != null) {
                GoodVersions gv = m_versionInfo.versions[bestVersionIndex];
                LogWrite($"다운 받을 크롬 드라이버 버전: {gv.version}");
                PlatformUrl[] PU = gv.downloads["chromedriver"];
                for (int i = 0; i < PU.Length; i++) {
                    if (PU[i].platform == "win64") {
                        downloadUrl = PU[i].url;
                        break;
                    }
                }
            } else {
                return null;
            }

            if (string.IsNullOrEmpty(downloadUrl) == false) {
                string downloadZipFileFullPath = Path.Combine(Path.GetTempPath(), ChromeDriverZipFileName);
                DownloadFile(downloadUrl, downloadZipFileFullPath);
                return downloadZipFileFullPath;
            } else {
                return null;
            }

        }

        internal string GetNewChromeDriverFromZipFile(string zipFileDownloadPath) {
            string unzipPath = Path.Combine(Path.GetDirectoryName(zipFileDownloadPath), Path.GetFileNameWithoutExtension(zipFileDownloadPath));

            UnzipFile(zipFileDownloadPath, unzipPath, true);

            return FindNewChromeDriverFullPathFromUnzipPath(unzipPath);
        }

        internal string FindNewChromeDriverFullPathFromUnzipPath(string chromeDriverUnzipPath) {
            chromeDriverUnzipPath += "\\chromedriver-win64";
            DirectoryInfo directoryInfo = new DirectoryInfo(chromeDriverUnzipPath);

            FileInfo[] files = directoryInfo.GetFiles();

            LogWrite(chromeDriverUnzipPath);
            foreach (FileInfo file in files) {
                // ignore case
                if (file.Name.ToLower() == ChromeDriverName.ToLower()) {
                    string newPath = Path.Combine(Path.GetDirectoryName(chromeDriverUnzipPath), file.Name);

                    File.Copy(file.FullName, newPath, true);

                    Directory.Delete(chromeDriverUnzipPath, true);

                    return newPath;
                }
                LogWrite($"찾은 파일 : {file.FullName}");
            }

            return null;
            //throw new Exception("Can't find chromedriver name. name: " + ChromeDriverName.ToLower());
        }

        internal void DownloadFile(string downloadUrl, string downloadPath) {
            new WebClient().DownloadFile(downloadUrl, downloadPath);
        }

        internal void UnzipFile(string zipPath, string unzipPath, bool deleteZipFile = true) {
            if (Directory.Exists(unzipPath)) {
                Directory.Delete(unzipPath, true);
            }

            ZipFile.ExtractToDirectory(zipPath, unzipPath);

            if (deleteZipFile) {
                File.Delete(zipPath);
            }
        }
    }
}


사진 및 파일 첨부

여기에 파일을 끌어 놓거나 왼쪽의 버튼을 클릭하세요.

파일 용량 제한 : 0MB (허용 확장자 : *.*)

0개 첨부 됨 ( / )

List of Articles
번호 분류 제목 글쓴이 날짜 조회 수
47 그외 게임 메이커 스튜디오 C# dll 라이브러리 만들 때 .NET 프레임워크 버전 문제 file 조루나 2024.05.03 3
46 게임 애드몹 Code 3 no fill 에러 원인 중 한 가지 file 조루나 2024.01.16 18
45 게임 유니티 특) 9 Slice랑 Filled 동시에 안 됨. 조루나 2023.11.29 10
44 게임 메쉬로 Progress circle 그리기 file 조루나 2023.11.23 10
» 그외 남이 만든 게 안 돌아가서 뜯어고친 C# 셀레니움 크롬 드라이버 자동 업데이트 조루나 2023.11.23 10
42 게임 우효, 이런 좋은 버그리포트 도구가 있었다니 Sentry 1 file 조루나 2023.05.08 43
41 게임 Unity 빌드 전 대화상자 출력 조루나 2023.04.20 10
40 게임 유니티 모바일에서 VideoPlayer로 영상 재생하면 자꾸 멈춘다. 조루나 2023.02.23 33
39 게임 세 가지 셀 셰이딩 에셋의 단순 프레임 비교 file 조루나 2023.02.03 43
38 게임 유니티 transform 참조의 문제 file 조루나 2022.11.10 63
37 게임 에셋 Super Tilemap Editor가 바닥면 Collider를 만들어주지 않아 file 조루나 2022.10.27 10
36 게임 미소녀 뱀파이어 서바이버즈를 만들자! - 캐릭터 몸에 마법 문신 넣기 file 조루나 2022.10.06 98
35 게임 Unity 2020에서 Spine 3.6 Runtime이 AtlasAsset을 제대로 Import하지 못 할 때 file 조루나 2022.09.20 19
34 게임 스파인 텍스쳐 런타임 색칠하기 file 조루나 2022.09.02 25
33 비주얼 블렌더 맛보기 1 file 조루나 2022.07.21 70
32 게임 파티클 메쉬와 Optimize Mesh Data의 저주 file 조루나 2022.07.14 20
31 게임 유니티 2D(2.5D) 타일 에셋 - Super Tilemap Editor file 조루나 2022.07.06 25
30 게임 유니티 컬러 스페이스와 스파인 HSL 색 변경의 역습 file 조루나 2022.07.06 126
29 게임 앱 이름에 따라 프레임이 다르게 나온다... file 조루나 2022.06.21 15
28 게임 유니티 스파인 슬롯에 HSL 색상 변경(=포토샵 Colorize) 3 file 조루나 2022.05.13 170
Board Pagination Prev 1 2 3 Next
/ 3