您的位置:首页 > 运维架构 > 网站架构

C# winform的WebBrowser自动登录某网站

2017-09-15 15:08 549 查看
最近项目需要接入别人的系统,需要自动登录,大概思路是:自动填写给定的用户名密码,模拟点击登录按钮;

代码如下:

HtmlElement elmUserName = web.Document.GetElementById(UserNameField);

if (elmUserName != null) elmUserName.SetAttribute("value", UserNameValue);

HtmlElement elmPWD = web.Document.GetElementById(PasswordField);

if (elmPWD != null) elmPWD.SetAttribute("value", PasswordValue);

 HtmlElementCollection hecs = web.Document.GetElementsByTagName("button");

 foreach (HtmlElement hec in hecs)

   {

     if (hec.Name == loginButtonName)

       {

         HtmlElement login = hec;

         if (login != null)

            login.InvokeMember("click");

             }

     }

后来遇到有的网站用到了JQuery EasyUI的控件,无法使用上述方法自动登录,需要稍改一下

 HtmlElement elmUserName = web.Document.GetElementById(UserNameField);

                    if (elmUserName != null) elmUserName.SetAttribute("value",UserNameValue);

                    HtmlElement elmPWD =PasswordField);

                    if (elmPWD != null) elmPWD.SetAttribute("value",PasswordValue);

                    HtmlElementCollection hec = web.Document.GetElementsByTagName("input");

                    foreach (HtmlElement he in hec)

                    {

                        if (he.Name == "Password")

                        {

                            he.SetAttribute("value",PasswordValue);

                            break;

                        }

                    }

                    HtmlElement loginHe = web.Document.GetElementById(AFieldName);

                    if (loginHe != null) loginHe.InvokeMember("click");
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息