C# How to use web browser control to automate login to a site

T.Zacks 3,991 Reputation points
2021-06-16T20:31:59.453+00:00

I was trying to login to a site programmatically. i am loading site into web browser control. i tried this code but it did not worked.

here is login page url login page url

Sorry could not share actual credentials.

HtmlElement username = null;  
HtmlElement password = null;  
HtmlElement submit = null;  
  
foreach (HtmlElement divcontainer in webBrowser1.Document.GetElementsByTagName("div"))  
{  
    if (divcontainer.GetAttribute("className") == "text-input")  
    {  
        foreach (HtmlElement child in divcontainer.Children)  
        {  
            if (divcontainer.GetAttribute("className") == "js-email-input")  
            {  
                username = divcontainer;  
            }  
  
            if (divcontainer.GetAttribute("className") == "password js-password-input")  
            {  
                password = divcontainer;  
            }  
        }  
    }  
  
    if (divcontainer.GetAttribute("className") == "sign-in")  
    {  
        foreach (HtmlElement child in divcontainer.Children)  
        {  
            if (divcontainer.GetAttribute("className") == "solid-button basic-login-submit")  
            {  
                submit = divcontainer;  
            }  
        }  
    }  
}  
  
if (username != null && password != null && submit != null)  
{  
    username.SetAttribute("value", "anon@user ");  
    password.SetAttribute("value", "test11");  
    submit.InvokeMember("click");  
}  

please some one guide me what to change in my code to automate login. where is wrong in my code. Thanks.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,819 questions
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.