Files
BokbonSample/BokBonCheck/ChromeDriverManager.cs
2025-06-28 22:14:18 +09:00

378 lines
15 KiB
C#

using System;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
using WebDriverManager;
using WebDriverManager.DriverConfigs.Impl;
using System.Reflection;
using System.Net.Http;
using System.Threading;
using System.IO.Compression;
namespace BokBonCheck
{
public static class ChromeDriverManager
{
private static string _driverPath = null;
public static async Task<string> SetupChromeDriverAsync(DownloadProgressForm progressForm = null)
{
try
{
// Chrome 버전 확인
var chromeVersion = GetChromeVersion();
Console.WriteLine($"설치된 Chrome 버전: {chromeVersion}");
if (progressForm != null)
{
progressForm.UpdateProgress(10, $"Chrome 버전 확인 중... ({chromeVersion})");
}
// 기존 드라이버 경로 확인
var existingDriverPath = GetExistingDriverPath();
if (!string.IsNullOrEmpty(existingDriverPath) && File.Exists(existingDriverPath))
{
Console.WriteLine($"기존 드라이버 발견: {existingDriverPath}");
// 기존 드라이버 테스트
if (await TestExistingDriver(existingDriverPath))
{
if (progressForm != null)
{
progressForm.UpdateProgress(100, "기존 드라이버 사용");
progressForm.SetCompleted("기존 드라이버를 사용합니다.");
}
_driverPath = existingDriverPath;
Environment.SetEnvironmentVariable("webdriver.chrome.driver", existingDriverPath);
return existingDriverPath;
}
else
{
Console.WriteLine("기존 드라이버 테스트 실패 - 새로 다운로드");
// 기존 드라이버가 작동하지 않으면 삭제
try
{
File.Delete(existingDriverPath);
Console.WriteLine("기존 드라이버 삭제됨");
}
catch (Exception ex)
{
Console.WriteLine($"기존 드라이버 삭제 실패: {ex.Message}");
}
}
}
if (progressForm != null)
{
progressForm.UpdateProgress(30, "Chrome 버전에 맞는 드라이버 다운로드 중...");
}
// WebDriverManager를 사용하여 설치된 Chrome 버전에 맞는 드라이버 다운로드
var driverManager = new DriverManager();
var driverPath = driverManager.SetUpDriver(new ChromeConfig(), "MatchingBrowser");
// 다운로드된 드라이버 경로 저장
_driverPath = driverPath;
// 환경 변수 설정
Environment.SetEnvironmentVariable("webdriver.chrome.driver", driverPath);
if (progressForm != null)
{
progressForm.UpdateProgress(100, "드라이버 다운로드 완료");
progressForm.SetCompleted("드라이버 다운로드 완료!");
}
Console.WriteLine($"ChromeDriver 경로: {driverPath}");
Console.WriteLine($"환경 변수 설정: webdriver.chrome.driver = {driverPath}");
return driverPath;
}
catch (Exception ex)
{
Console.WriteLine($"ChromeDriver 설정 오류: {ex.Message}");
if (progressForm != null)
{
progressForm.SetError($"설정 오류: {ex.Message}");
}
throw;
}
}
private static string GetExistingDriverPath()
{
try
{
// 환경 변수에서 확인
var envPath = Environment.GetEnvironmentVariable("webdriver.chrome.driver");
if (!string.IsNullOrEmpty(envPath) && File.Exists(envPath))
{
return envPath;
}
// WebDriverManager 캐시 폴더에서 확인
var cachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".cache", "selenium");
if (Directory.Exists(cachePath))
{
var chromeDriverFiles = Directory.GetFiles(cachePath, "chromedriver*", SearchOption.AllDirectories);
foreach (var file in chromeDriverFiles)
{
if (file.EndsWith(".exe") || !Path.HasExtension(file))
{
return file;
}
}
}
return null;
}
catch
{
return null;
}
}
public static string GetDriverPath()
{
return _driverPath;
}
private static string GetChromeVersion()
{
try
{
// Windows에서 Chrome 설치 경로 확인
var chromePaths = new[]
{
@"C:\Program Files\Google\Chrome\Application\chrome.exe",
@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
@"Google\Chrome\Application\chrome.exe")
};
foreach (var path in chromePaths)
{
if (File.Exists(path))
{
var versionInfo = FileVersionInfo.GetVersionInfo(path);
var version = versionInfo.FileVersion;
Console.WriteLine($"Chrome 버전 감지: {version} (경로: {path})");
return version;
}
}
return "알 수 없음";
}
catch (Exception ex)
{
Console.WriteLine($"Chrome 버전 감지 실패: {ex.Message}");
return "확인 실패";
}
}
public static bool IsChromeInstalled()
{
try
{
var chromePaths = new[]
{
@"C:\Program Files\Google\Chrome\Application\chrome.exe",
@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
@"Google\Chrome\Application\chrome.exe")
};
foreach (var path in chromePaths)
{
if (File.Exists(path))
{
return true;
}
}
return false;
}
catch
{
return false;
}
}
public static async Task<bool> TestChromeDriverAsync(DownloadProgressForm progressForm = null)
{
try
{
var driverPath = await SetupChromeDriverAsync(progressForm);
if (progressForm != null)
{
progressForm.UpdateProgress(50, "드라이버 테스트 중...");
}
// ChromeDriver 서비스 설정
var service = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService(Path.GetDirectoryName(driverPath));
service.HideCommandPromptWindow = true;
// 간단한 테스트 실행
var options = new OpenQA.Selenium.Chrome.ChromeOptions();
options.AddArgument("--headless");
options.AddArgument("--no-sandbox");
options.AddArgument("--disable-dev-shm-usage");
options.AddArgument("--disable-gpu");
options.AddArgument("--remote-debugging-port=0");
using (var driver = new OpenQA.Selenium.Chrome.ChromeDriver(service, options))
{
driver.Navigate().GoToUrl("https://www.google.com");
var title = driver.Title;
Console.WriteLine($"드라이버 테스트 성공: {title}");
if (progressForm != null)
{
progressForm.UpdateProgress(100, "드라이버 테스트 성공!");
progressForm.SetCompleted("드라이버 테스트 성공!");
}
return !string.IsNullOrEmpty(title);
}
}
catch (Exception ex)
{
Console.WriteLine($"ChromeDriver 테스트 실패: {ex.Message}");
if (progressForm != null)
{
progressForm.SetError($"테스트 실패: {ex.Message}");
}
return false;
}
}
public static void ClearDriverCache()
{
try
{
Console.WriteLine("Chrome 드라이버 캐시 정리 시작...");
// WebDriverManager 캐시 폴더 정리
var cachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
".cache", "selenium");
if (Directory.Exists(cachePath))
{
Directory.Delete(cachePath, true);
Console.WriteLine($"WebDriverManager 캐시 정리됨: {cachePath}");
}
// 환경 변수에서 설정된 드라이버 경로도 정리
var envDriverPath = Environment.GetEnvironmentVariable("webdriver.chrome.driver");
if (!string.IsNullOrEmpty(envDriverPath) && File.Exists(envDriverPath))
{
try
{
File.Delete(envDriverPath);
Console.WriteLine($"환경 변수 드라이버 삭제됨: {envDriverPath}");
}
catch (Exception ex)
{
Console.WriteLine($"환경 변수 드라이버 삭제 실패: {ex.Message}");
}
}
// 저장된 드라이버 경로도 정리
if (!string.IsNullOrEmpty(_driverPath) && File.Exists(_driverPath))
{
try
{
File.Delete(_driverPath);
Console.WriteLine($"저장된 드라이버 삭제됨: {_driverPath}");
}
catch (Exception ex)
{
Console.WriteLine($"저장된 드라이버 삭제 실패: {ex.Message}");
}
}
_driverPath = null;
Environment.SetEnvironmentVariable("webdriver.chrome.driver", null);
Console.WriteLine("Chrome 드라이버 캐시 정리 완료");
}
catch (Exception ex)
{
Console.WriteLine($"캐시 정리 실패: {ex.Message}");
}
}
public static bool IsDriverReady()
{
try
{
var driverPath = GetExistingDriverPath();
if (string.IsNullOrEmpty(driverPath) || !File.Exists(driverPath))
{
Console.WriteLine("기존 드라이버가 없습니다.");
return false;
}
Console.WriteLine($"드라이버 준비 상태 확인: {driverPath}");
// 간단한 테스트 실행
var service = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService(Path.GetDirectoryName(driverPath));
service.HideCommandPromptWindow = true;
var options = new OpenQA.Selenium.Chrome.ChromeOptions();
options.AddArgument("--headless");
options.AddArgument("--no-sandbox");
options.AddArgument("--disable-dev-shm-usage");
options.AddArgument("--disable-gpu");
options.AddArgument("--remote-debugging-port=0");
using (var driver = new OpenQA.Selenium.Chrome.ChromeDriver(service, options))
{
driver.Navigate().GoToUrl("https://www.google.com");
var result = !string.IsNullOrEmpty(driver.Title);
Console.WriteLine($"드라이버 준비 상태: {(result ? "" : "")}");
return result;
}
}
catch (Exception ex)
{
Console.WriteLine($"드라이버 준비 상태 확인 실패: {ex.Message}");
return false;
}
}
private static async Task<bool> TestExistingDriver(string driverPath)
{
try
{
Console.WriteLine($"기존 드라이버 테스트: {driverPath}");
// ChromeDriver 서비스 설정
var service = OpenQA.Selenium.Chrome.ChromeDriverService.CreateDefaultService(Path.GetDirectoryName(driverPath));
service.HideCommandPromptWindow = true;
// 간단한 테스트 실행
var options = new OpenQA.Selenium.Chrome.ChromeOptions();
options.AddArgument("--headless");
options.AddArgument("--no-sandbox");
options.AddArgument("--disable-dev-shm-usage");
options.AddArgument("--disable-gpu");
options.AddArgument("--remote-debugging-port=0");
using (var driver = new OpenQA.Selenium.Chrome.ChromeDriver(service, options))
{
driver.Navigate().GoToUrl("https://www.google.com");
var title = driver.Title;
Console.WriteLine($"드라이버 테스트 성공: {title}");
return !string.IsNullOrEmpty(title);
}
}
catch (Exception ex)
{
Console.WriteLine($"기존 드라이버 테스트 실패: {ex.Message}");
return false;
}
}
}
}