.net Selenium 截图

2)使用Package Manager命令安装

PM> Install-Package Selenium.Support -Version 3.141.0
PM> Install-Package Selenium.Chrome.WebDriver -Version 79.0.0

3)使用.NET CLI命令安装

> dotnet add package Selenium.Support -Version 3.141.0
> dotnet add package Selenium.Chrome.WebDriver --version 79.0.0

2、载取可视区域图片

  public static void PageScreenshot(string url,string path)
        {
            ChromeDriver driver = null;
            try
            {
                ChromeOptions options = new ChromeOptions();
                options.AddArguments("headless", "disable-gpu");
                 driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), options);
                driver.Navigate().GoToUrl(url);
                var screenshot = (driver as ITakesScreenshot).GetScreenshot();
                screenshot.SaveAsFile(path);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message+Environment.NewLine+ex.StackTrace);
            }
            finally
            {
                if (driver != null)
                {
                    driver.Close();
                    driver.Quit();
                }
            }
        }

3、载取有滚动条网页长图

        public static void PageScreenshot(string url,string path)
        {
            ChromeDriver driver = null;
            try
            {
                ChromeOptions options = new ChromeOptions();
                options.AddArguments("headless", "disable-gpu");
                driver = new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), options);
                driver.Navigate().GoToUrl(url);
                string width = driver.ExecuteScript("return document.body.scrollWidth").ToString();
                string height = driver.ExecuteScript("return document.body.scrollHeight").ToString();
                driver.Manage().Window.Size = new System.Drawing.Size(int.Parse(width), int.Parse(height)); //=int.Parse( height);
                var screenshot = (driver as ITakesScreenshot).GetScreenshot();
                screenshot.SaveAsFile(path);
            }
            catch (Exception ex)
            {
                logger.Error(ex.Message+Environment.NewLine+ex.StackTrace);
            }
            finally
            {
                if (driver != null)
                {
                    driver.Close();
                    driver.Quit();
                }
            }
        }
posted @ 2023-03-10 23:28  桃花雪  阅读(30)  评论(0编辑  收藏  举报