Search code examples
c#authenticationhtmlelements

Cannot Login into a website programmatically using webbrowser in c#


I have tried to log in into a website ("https://mytel.com.mm/") with webbrowser in c#. It cannot be logged in. Below is the code.

/// <summary>
    /// The main entry point for the application.
    /// </summary>
    private static WebBrowser wb;
    [STAThread]
    static void Main()
    {
        wb = new WebBrowser();
        wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted);
        wb.Navigate("https://mytel.com.mm/");

        Application.Run();
    }
    static void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        string Logurl = wb.Url.AbsoluteUri;
        if (!wb.Url.ToString().Contains("myviettel"))
        {
            var InputElements = wb.Document.GetElementsByTagName("input");
            foreach (HtmlElement i in InputElements)
            {
                if (i.GetAttribute("ng-model").Equals("loginForm.username"))
                {
                    i.Focus();
                    i.InnerText = "xxxxxxxxx";
                }
                if (i.GetAttribute("ng-model").Equals("loginForm.password"))
                {
                    i.Focus();
                    i.InnerText = "xxxxxxxxx";
                    i.RemoveFocus();
                }
            }

            var buttonElements = wb.Document.GetElementsByTagName("button");
            foreach (HtmlElement b in buttonElements)
            {
                if (b.GetAttribute("className").Equals("btn btn-nat-input-popup-bottom margin-bottom-10 ng-binding"))
                {
                    b.InvokeMember("click");
                }
            }
        }
        else
        {
            //logged in
        }
    }

After successful login, the url is "https://www.mytel.com.mm/myviettel".
And I think Logurl variable should contain ("https://www.mytel.com.mm/myviettel").

Thank you


Solution

  • For the sake of the answers, I use Selenium Chromedriver service which can be successfully login programmatically.