WebBrowser小示例(一)

最近工作中要做一个网页交费接口,用到了WebBrowser,在网上也查了一些相关介绍,做了一个小例子:

一、在项目中加入WebBrowser控件,并load事件中绑定到相应网站,这里我以校内网的登录介面为例:

webBrowser1.Url  =   new  Uri( " http://www.renren.com/SysHome.do " );

 

这样当你运行程序就会定位到校内网的登录页面;

二、winform与web页面的交互:

进入校内登录页面后,接下来我们来完成在winform程序中登录校内个人主页。查看校内的登录页面的源文件我们会发现:

代码
< form method = " post "  id = " loginForm "   class = " login-form "  action = " http://www.renren.com/PLogin.do "   >
< class = " top " >
< label  for = " email " > 帐号: </ label >
< input type = " text "  name = " email "   class = " input-text "  id = " email "  tabindex = " 1 "  value = "" />
</ p >
< p >
< label  for = " password " > 密码: </ label >
< input type = " password "  id = " password "  name = " password "  error = " 请输入密码 "   class = " input-text "  tabindex = " 2 "    />
</ p >
< div  class = " caps-lock-tips "  id = " capsLockMessage "  style = " display:none " ></ div >
< p >
< label title = " 为了确保您的信息安全,请不要在网吧或者公共机房勾选此项! "   class = " labelCheckbox " >
< input type = " checkbox "  name = " autoLogin "  id = " autoLogin "  value = " true "  tabindex = " 3 "   /> 下次自动登录
</ label >
</ p >
< class = " bottom " >
< class = " float-right "  href = " http://safe.renren.com/findPass.do " > 找回密码 </ a >< input type = " hidden "  name = " origURL "  value = " http://www.renren.com/Home.do "   />
< input type = " hidden "  name = " domain "  value = " renren.com "   />
< input type = " submit "  id = " login "    class = " input-submit "  value = " 登录 "  tabindex = " 4 "   />
</ p >
</ form >

 

 

我们要做的就是取得<form>内的而要我们填充登录信息的元素:我们看到上面有"账号:"它对应的就是我们登录校内时的个人账户:我们要做的就是在<input>中写入我们的账户,不过首先我们要获取这个元素以便对它赋值:而.net 也给我们提供了这个方法:

 

HtmlElement name  =  webBrowser1.Document.All[ " email " ];

 

HtmlElement对象,All["这里要填写的就是网页中文本输入框的id或name"];

接下来我们就可以为账户赋值了:

name.SetAttribute( " value " , txtname.Text.ToString());

 

其中txtname.Text.ToString()就是校内账户,同样密码也是同样;

接下来就是登录了可以看一下登录按钮:

<input type="submit" id="login"  class="input-submit" value="登录" tabindex="4" />
它的获取同上,如何执行这个事件:

 

btnsubmit.InvokeMember( " click " );

 

其中btnsubmit是和name一样的HtmlElement对象。上而这句就完成了按钮的单击事件;简单的winform登录web页面就完成了,下面是完整的代码:

 

 

代码
HtmlElement name  =  webBrowser1.Document.All[ " email " ];
            HtmlElement pwd 
=  webBrowser1.Document.All[ " password " ];
            HtmlElement formlogin 
=  webBrowser1.Document.Forms[ " loginForm " ];
            
if  (formlogin  ==   null   ||  name  ==   null   ||  pwd  ==   null )
            {
                MessageBox.Show(
" 页面读取出错! " );
                
return ;
            }
            name.SetAttribute(
" value " , txtname.Text.ToString());
            pwd.SetAttribute(
" value " , txtpwd.Text.ToString());
            btnsubmit.InvokeMember(
" click " );
           

 

就先到这儿,有时间再把读取页面的内容添进来

你可能感兴趣的:(WebBrowser)