如何使用Selenium-Chrome(“ --headless”)截屏

时间:2019-06-10 13:22:30

标签: selenium screenshot webpage-screenshot

我已经使用Selenium创建了一个应用程序。该应用程序将打开chrome,并访问3个不同的网站并捕获屏幕截图。一切都很好。但是,只要添加无头参数,以便chrome在后台运行,应用程序就会继续运行并保存第一个图片,但是当它转到第二个网站时,它将在此行中向我抛出系统内存不足异常“内存不足”代码(“使用(var clone = screenshot.Clone(croppedImage,screenshot.PixelFormat))”)。

如果有人可以向我指出要解决这个问题我必须做/应该读些什么。

public void TakeScreenshot(IWebDriver driver, IWebElement element, string filename)
        {
            // Scroll to the element if necessary
            var actions = new Actions(driver);
            actions.MoveToElement(element);
            actions.Perform();
            // Get the element position (scroll-aware)
            var locationWhenScrolled = ((RemoteWebElement)element).LocationOnScreenOnceScrolledIntoView;
            var fileName = filename + ".png";
            var byteArray = ((ITakesScreenshot)driver).GetScreenshot().AsByteArray;
            Class_Timer.MyTimer();
            using (var screenshot = new System.Drawing.Bitmap(new System.IO.MemoryStream(byteArray)))
            {
                var location = locationWhenScrolled;
                // Fix location if necessary to avoid OutOfMemory Exception
                if (location.X + element.Size.Width > screenshot.Width)
                {
                    location.X = screenshot.Width - element.Size.Width;
                }
                if (location.Y + element.Size.Height > screenshot.Height)
                {
                    location.Y = screenshot.Height - element.Size.Height;
                }
                Class_Timer.MyTimer();
                // Crop the screenshot
                var croppedImage = new System.Drawing.Rectangle(location.X, location.Y, element.Size.Width, element.Size.Height);
                using (var clone = screenshot.Clone(croppedImage, screenshot.PixelFormat))
                {
                    clone.Save(fileName, ImageFormat.Png);
                    Class_Timer.MyTimer();
                    clone.Dispose(); 

                }
                screenshot.Dispose();
            }

        }

0 个答案:

没有答案