获取网页中的验证码图片

首先需要添加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部分源代码

Registration Verification Code

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


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



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

你可能感兴趣的:(获取网页中的验证码图片)