ChromeDriver截图

时间:2024-07-11 00:07:44

一、NuGet安装Selenium.Chrome.WebDriver和Selenium.WebDriver

二、将packages\Selenium.Chrome.WebDriver.2.45\driver下的chromedriver.exe文件,复制到程序的bin目录下

三、截图工具类

using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using System.ComponentModel.Design;
using System.Drawing;
using System.IO;
using System.Threading; namespace Comon
{
public class ScreenshotUtil : IDisposable
{
/// <summary>
/// 锁
/// </summary>
private static readonly object LockObject = new object(); private static IWebDriver _webDriver; public ScreenshotUtil(string url, int windowWidth, int windowHeight)
{
if (_webDriver == null)
{
lock (LockObject)
{
if (_webDriver == null)
{
ChromeOptions options = new ChromeOptions();
options.AddArgument($"--window-size={windowWidth},{windowHeight}");
options.AddArgument("start-fullscreen");
_webDriver = new ChromeDriver(options);
}
}
}
if (_webDriver.Url != url)
{
_webDriver.Navigate().GoToUrl(url);
}
} public void Dispose()
{
_webDriver?.Quit();
_webDriver = null;
} public static void Quit()
{
lock (LockObject)
{
_webDriver?.Quit();
_webDriver = null;
}
} public void ShotThenSave(string targetFileName, TimeSpan waitTime, Func<IWebDriver, IWebElement> condition)
{
if (!File.Exists(targetFileName))
{
lock (LockObject)
{
if (string.IsNullOrWhiteSpace(targetFileName))
{
throw new ArgumentNullException(nameof(targetFileName));
}
if (condition != null)
{
WebDriverWait webDriverWait = new WebDriverWait(_webDriver, waitTime);
webDriverWait.Until(condition);
} Thread.Sleep(); ITakesScreenshot screenshotDriver = (ITakesScreenshot)_webDriver;
if (screenshotDriver != null)
{
Screenshot screenshot = screenshotDriver.GetScreenshot();
string directoryName = Path.GetDirectoryName(targetFileName);
if (directoryName == null)
{
throw new ArgumentException(nameof(targetFileName));
}
if (!Directory.Exists(directoryName))
{
Directory.CreateDirectory(directoryName);
}
ClearOldImage(directoryName); screenshot.SaveAsFile(targetFileName);
}
}
}
} private static void ClearOldImage(string directoryName)
{
DirectoryInfo folder = new DirectoryInfo(directoryName);
FileInfo[] existFileInfos = folder.GetFiles();
if (existFileInfos.Length > )
{
foreach (var file in existFileInfos)
{
if (file.CreationTime < DateTime.Today)
{
try
{
file.Delete();
}
catch (Exception e)
{
LogUtil.LogException(e);
} }
}
}
}
}
}