如何获取WatiN图像元素的位图?

Dan*_*l G 6 .net c# watin

我有一些文本字段处理和其他元素,但我想得到位图,所以我可以将它保存在磁盘上的某个地方.如果可能的话,我需要直接从WatiN进行.

我怎样才能做到这一点?

Bru*_*uno 7

我前段时间遇到过类似的问题.Watin无法直接执行此操作,但它会公开获取某些结果所需的mshtml对象.

当时我的代码非常像这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WatiN.Core;
using WatiN.Core.Native.InternetExplorer;
using mshtml;
using System.Windows.Forms;

namespace ConsoleApplication1
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            Browser browser = new IE("http://www.google.com");
            IEElement banner = browser.Images[0].NativeElement as IEElement;

            IHTMLElement bannerHtmlElem = banner.AsHtmlElement;
            IEElement bodyNative = browser.Body.NativeElement as IEElement;
            mshtml.IHTMLElement2 bodyHtmlElem = (mshtml.IHTMLElement2)bodyNative.AsHtmlElement;
            mshtml.IHTMLControlRange controlRange = (mshtml.IHTMLControlRange)bodyHtmlElem.createControlRange();

            controlRange.add((mshtml.IHTMLControlElement)bannerHtmlElem);
            controlRange.execCommand("Copy", false, System.Reflection.Missing.Value);
            controlRange.remove(0);

            if (Clipboard.GetDataObject() != null)
            {
                IDataObject data = Clipboard.GetDataObject();
                if (data.GetDataPresent(DataFormats.Bitmap))
                {
                    System.Drawing.Image image = (System.Drawing.Image)data.GetData(DataFormats.Bitmap, true);
                    // do something here
                }
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

基本上,这个小黑客试图将图像复制到剪贴板.但是我遇到了一些问题,使其正常工作,最终快照图像周围的区域并将其保存到磁盘.

虽然这可能不是很有帮助,但它可能会指向某些方向..


Bap*_*net 5

我认为你不能直接从WatiN获取二进制信息.但是,您有Image.Uri方法为您提供图像的URI.因此,很容易下载它与http请求.

using (Browser browser = new IE("http://www.sp4ce.net/computer/2011/01/06/how-to-use-WatiN-with-NUnit.en.html"))
{
   Image image = browser.Images[0];
   Console.Write(image.Uri);

   HttpWebRequest request = (HttpWebRequest)WebRequest.Create(image.Uri);
   WebResponse response = request.GetResponse();
   using (Stream stream = response.GetResponseStream())
   using (FileStream fs = File.OpenWrite(@"c:\foo.png"))
   {
      byte[] bytes = new byte[1024];
      int count;
      while((count = stream.Read(bytes, 0, bytes.Length))!=0)
      {
         fs.Write(bytes, 0, count);
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助

  • 是的我可以使用它,但每次请求图像都在变化... PHP代码会在每个请求上生成新图像,因此我需要与WatiN完全相同.也许一些绑定到IHtmlDocument或什么? (2认同)