小程序的演示效果如下:
这段是获取HTML源代码的方法:
private void btnShowCode_Click(object sender, System.EventArgs e)
{
System.Net.WebRequest myWebRequest=System.Net.WebRequest.Create(this.txtURL.Text);
myWebRequest.Timeout=5000;
string _htmlCode="";
try
{
System.Net.WebResponse myWebR=myWebRequest.GetResponse();
System.IO.Stream resStream=myWebR.GetResponseStream();
System.IO.StreamReader sr=new System.IO.StreamReader(resStream,System.Text.Encoding.Default);
_htmlCode=sr.ReadToEnd();
resStream.Close();
sr.Close();
this.txtCode.Text=_htmlCode;
}
catch(System.Net.WebException ex)
{
this.txtCode.Text=ex.Message;
}
getValidateCode(_htmlCode);
}
{
System.Net.WebRequest myWebRequest=System.Net.WebRequest.Create(this.txtURL.Text);
myWebRequest.Timeout=5000;
string _htmlCode="";
try
{
System.Net.WebResponse myWebR=myWebRequest.GetResponse();
System.IO.Stream resStream=myWebR.GetResponseStream();
System.IO.StreamReader sr=new System.IO.StreamReader(resStream,System.Text.Encoding.Default);
_htmlCode=sr.ReadToEnd();
resStream.Close();
sr.Close();
this.txtCode.Text=_htmlCode;
}
catch(System.Net.WebException ex)
{
this.txtCode.Text=ex.Message;
}
getValidateCode(_htmlCode);
}
通过正则表达式获得其中用户登陆的验证码:
private void getValidateCode(string htmlCode)
{
string pattern=@"[>]\d{4}[<]";
System.Text.RegularExpressions.Regex regex=new System.Text.RegularExpressions.Regex(pattern);
System.Text.RegularExpressions.Match match=regex.Match(htmlCode);
if(match.Success)
{
this.txtValidateCode.Text=match.Value.Substring(1,4);
}
else
{
this.txtValidateCode.Text="null";
}
}
{
string pattern=@"[>]\d{4}[<]";
System.Text.RegularExpressions.Regex regex=new System.Text.RegularExpressions.Regex(pattern);
System.Text.RegularExpressions.Match match=regex.Match(htmlCode);
if(match.Success)
{
this.txtValidateCode.Text=match.Value.Substring(1,4);
}
else
{
this.txtValidateCode.Text="null";
}
}