简体   繁体   English

C#Selenium Webdriver-如何保存特定图像,而不管位置

[英]C# selenium webdriver - How to save a specific image regardless of location

I've seen a ton of examples how to save an image based on saving a screenshot. 我已经看到了很多示例,这些示例基于保存屏幕截图来保存图像。

This has a fundamental flaw. 这有一个根本的缺陷。 The take screenshot only takes whats visable on the page at the time. 拍摄屏幕快照仅显示当时页面上显示的内容。 So if I have an image at the bottom of the page, and I want to save it based on the location of the elements that I found, either one or two problems occur. 因此,如果我在页面底部有一个图像,并且想根据找到的元素的位置保存它,则可能会发生一两个问题。

If I save the screenshot and then try to save by the location, the screen shot ends at point 1200 but the image is located at 3000. If i focus on the image and then take a screen shot, the image is is now on the screen shot, however, the location doesn't work. 如果我保存屏幕截图,然后尝试按位置保存,则屏幕快照在点1200处结束,但是图像位于3000点。如果我将焦点放在图像上然后进行屏幕截图,则图像现在在屏幕上拍摄,但是位置不起作用。 It doesn't work because I still have a 1200px height image with a location of 3000. 它不起作用,因为我仍然有一个1200px高度的图像,位置为3000。

How can I simply say, I have an image at 3000x 3014y and I just want to save it? 我怎样简单地说,我有一个3000x 3014y的图像,我只想保存它?

I've resolved it. 我已经解决了 Chrome vs IE vs Firefox take screen shots in different manners. Chrome vs IE vs Firefox以不同的方式拍摄屏幕快照。 Firefox will stitch the screenshot together, chrome only takes whats visible and IE will shrink everything to try to fit on one page. Firefox会将屏幕截图拼接在一起,Chrome仅显示可见内容,而IE会缩小所有内容以使其适合一页。

If you need to do a screenshot of something that is not on the base page i'd suggest firefox 如果您需要对基本页面上没有的内容进行屏幕截图,建议您使用Firefox

You can basically get base64 string of the image and save it to file. 您基本上可以获取图像的base64字符串并将其保存到文件中。

var base64string = driver.ExecuteScript(@"
    var c = document.createElement('canvas');
    var ctx = c.getContext('2d');
    var img = document.getElementsByTagName('img')[0];
    c.height=img.height;
    c.width=img.width;
    ctx.drawImage(img, 0, 0,img.width, img.height);
    var base64String = c.toDataURL();
    return base64String;
    ") as string;

var base64 = base64string.Split(',').Last();
using (var stream = new MemoryStream(Convert.FromBase64String(base64)))
{
    using (var bitmap = new Bitmap(stream))
    {
        var filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{Guid.NewGuid()}.jpg");
        bitmap.Save(filepath, ImageFormat.Jpeg);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM