龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > asp.net编程 >

C#高级应用:使用C#获取网页验证码图片的内容

时间:2009-12-21 11:47来源:未知 作者:admin 点击:
分享到:
有时候我们需要获得网页上的图片,尤其是向验证码这样的图片.这个方法就是将网页上的图片获取到PictureBox中.效果入下图所示. 右边是使用Webbrowser控件装载的某网站的注册页面,其中包
有时候我们需要获得网页上的图片,尤其是向验证码这样的图片.这个方法就是将网页上的图片获取到PictureBox中.效果入下图所示.

右边是使用Webbrowser控件装载的某网站的注册页面,其中包括了验证码.左边是获取到的验证码,装载在PictureBox中.也许有人会问,通过Webbrowser也能够看到注册页面的验证码为什么还要,在获得这个验证码.原因如下:当你不想让别人知道在做什么的时候需要使用,别人只能看到注册码而不知道在干什么事情;另外愿意是为了方便,当做这个一个注册程序的时候,注册信息一般都是自动生成的,但是验证码需要输入,不停的拖动滚动条找注册码的位置不方便.

下面看看如何实现.

首先需要添加mshtml的引用,之后using mshtml;
        public static Image GetRegCodePic(WebBrowser wbMail, string ImgName, string Src, string Alt)
        {
             HTMLDocument doc = (HTMLDocument)wbMail.Document.DomDocument;
             HTMLBody body = (HTMLBody)doc.body;
             IHTMLControlRange rang = (IHTMLControlRange)body.createControlRange();
             IHTMLControlElement Img;
            if (ImgName == "") //如果没有图片的名字,通过Src或Alt中的关键字来取
            {
                int ImgNum = GetPicIndex(wbMail, Src,Alt);
                if (ImgNum == -1) return null;
                 Img = (IHTMLControlElement)wbMail.Document.Images[ImgNum].DomElement;
             }
            else
                 Img = (IHTMLControlElement)wbMail.Document.All[ImgName].DomElement;

             rang.add(Img);
             rang.execCommand("Copy", false, null);
             Image RegImg = Clipboard.GetImage();
             Clipboard.Clear();
            return RegImg;
         }

        public static int GetPicIndex(WebBrowser wbMail, string Src, string Alt)
        {
            int imgnum = -1;
            for (int i = 0; i < wbMail.Document.Images.Count; i++) //获取所有的Image元素
            {
                 IHTMLImgElement img = (IHTMLImgElement)wbMail.Document.Images.DomElement;
                if (Alt == "")
                {
                    if (img.src.Contains(Src)) return i;
                 }
                else
                {
                    if (!string.IsNullOrEmpty(img.alt))
                    {
                        if (img.alt.Contains(Alt)) return i;
                     }
                 }
             }
            return imgnum;
         }


精彩图集

赞助商链接