现在的位置: 首页 > 综合 > 正文

获取网页中的验证码图片 。。。。。。。。。。

2012年09月25日 ⁄ 综合 ⁄ 共 2290字 ⁄ 字号 评论关闭
有时候我们需要获得网页上的图片,尤其是向验证码这样的图片.这个方法就是将网页上的图片获取到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 == -1return null;
                Img 
= (IHTMLControlElement)wbMail.Document.Images[ImgNum].DomElement;
            }

            
else
                Img 
= (IHTMLControlElement)wbMail.Document.All[ImgName].DomElement;

            rang.add(Img);
            rang.execCommand(
"Copy"falsenull);
            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[i].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;
        }

通过调用GetRegCodePic就可以获得注册码图片了.下面是几个示例.
示例1:
下面是某个站的注册码图片的HTML部分源代码

<IMG height=80 alt="Registration Verification Code" src="......" width=290 border=0>

picturebox1.Image =GetRegCodePic(wbMail, "", "", "Registration Verification Code")

示例2:
下面是某个站的注册码图片的HTML部分源代码

<IMG id=CAPTCHAImage src="......." name=CAPTCHAImage>

picturebox1.Image =GetRegCodePic(wbMail, "CAPTCHAImage", "", "")  //通过验证码Html元素的名字来取

抱歉!评论已关闭.