Manipulate page with WebBrowser

2

I'm having trouble sending values to a form via Web Browser . My goal is to make a post, that is, send the values to the inputs of the form and make the submit of it, after that open the page generated in my browser.

Form:

<form action="..." method="post" accept-charset="ISO-8859-1" name="postmodify" id="postmodify" class="flow_hidden" onsubmit="submitonce(this);smc_saveEntities('postmodify', ['subject', 'message', 'guestname', 'evtitle', 'question'], 'options');" enctype="multipart/form-data">

    <input type="text" name="subject" tabindex="1" size="80" maxlength="80" class="input_text" />


    <select name="icon" id="icon" onchange="showimage()">
        <option value="xx" selected="selected">Padrão</option>
        <option value="thumbup">OK</option>
        <option value="thumbdown">Negativo</option>
        <option value="exclamation">Ponto de exclamação</option>
        <option value="question">Ponto de interrogação</option>
        <option value="lamp">Lâmpada</option>
        <option value="smiley">Sorridente</option>
        <option value="angry">Zangado</option>
        <option value="cheesy">Contente</option>
        <option value="grin">Sorriso forçado</option>
        <option value="sad">Triste</option>
        <option value="wink">Piscar</option>
    </select>

    <textarea class="resizeble" name="message" id="message" rows="12" cols="600" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);" onchange="storeCaret(this);" tabindex="2" style="height: 175px; width: 100%; "></textarea>

    <input type="submit" value="Enviar" tabindex="3" onclick="return submitThisOnce(this);" accesskey="s" class="button_submit" />

</form>

C #:

WebBrowser oWebBrowser = new WebBrowser();
oWebBrowser.ScriptErrorsSuppressed = true;
oWebBrowser.Navigate("meulink");

//botão para fazer postagem
private void postar_Click(object sender, EventArgs e)
{
    try
    {
        HtmlElement subject = oWebBrowser.Document.GetElementsByTagName("input")["subject"];
        if(subject != null)
        {  //tentativa de setar o subject
            subject.SetAttribute("value", assunto);
            MessageBox.Show("assunto");
        }

        HtmlElement ico = oWebBrowser.Document.GetElementById("icon");
        if (ico != null)
        { //tentativa de setar o icon
            ico.SetAttribute("value", m.traduzIcon(icon.Text));
            MessageBox.Show("icon");
        }


        HtmlElement message = oWebBrowser.Document.GetElementById("message");
        if (message != null)
        { //tentativa de setar o message
            message.InnerText = padrao;
            MessageBox.Show("padrao");
        }


        HtmlElement form = oWebBrowser.Document.GetElementById("postmodify");
        if (form != null)
        { //tentativa de dar submit
            form.InvokeMember("submit");
            MessageBox.Show("submit");
        }
        //tentativa de abrir o link da postagem
        ProcessStartInfo post = new ProcessStartInfo(oWebBrowser.Url.AbsoluteUri);
        Process.Start(post);

    }
    catch
    {
        MessageBox.Show("ERRO");
    }
}

When running it does not display any MessageBox and opens my browser on the page defined in Web Browser ( meulink - the one that has the form). Can someone give me a help? I do not know how to do this right, I'm relying on surveys.

    
asked by anonymous 23.01.2016 / 19:08

1 answer

4

The method WebBrowser.Navigate load the page asynchronously, so you manipulate the document should wait for the document to be loaded.

You can do this in two ways:

  • Scheduling event WebBrowser.DocumentCompleted ( Solution quoted in this post )
  • Place the code below to ensure that the code does not progress until the page has been loaded (This must be done after the Navigate method and after the form.InvokeMember("submit"); call) (Solution quoted in this post ):
  • while (oWebBrowser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }

    I made an example working with the code below (It loads the Stackoverflow page and searches for a keyword). I created a simple Windows application with a form, a WebBrowser component (which named the WebBrowser just like you) and a button. All the code executes in the button click, which is below:

            private void button1_Click(object sender, EventArgs e)
            {
                //Resposta a pergunta http://pt.stackoverflow.com/questions/109853/manipular-p%C3%A1gina-com-webbrowser
                oWebBrowser.ScriptErrorsSuppressed = true;
                oWebBrowser.Navigate("https://stackoverflow.com/");
    
                //https://stackoverflow.com/questions/583897/c-sharp-how-to-wait-for-a-webpage-to-finish-loading-before-continuing
                while (oWebBrowser.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }
    
                //https://stackoverflow.com/questions/9925022/webbrowser-document-is-always-null
                MessageBox.Show(oWebBrowser.Document.Url.AbsoluteUri);
    
                HtmlElement questionInput = oWebBrowser.Document.GetElementById("q");
                if (questionInput != null)
                {
                    questionInput.SetAttribute("value", "WebBrowser");
                    MessageBox.Show("encontrou o campo valor");
                }
    
                HtmlElement questionForm = oWebBrowser.Document.GetElementById("search");
                if (questionInput != null)
                {
                    questionForm.InvokeMember("submit");
                    MessageBox.Show("Fez submit");
                }
                while (oWebBrowser.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }    
                MessageBox.Show(oWebBrowser.Document.Url.AbsoluteUri);
    
                //https://stackoverflow.com/questions/2299273/how-do-i-submit-a-form-inside-a-webbrowser-control
            }
    

    Edit1:

    I think you should be having trouble selecting the control correctly. I applied the same idea of solution above on the login page that you mentioned and really had to take some care to find the controls and set the values.

    Tips for you: If I were looking for an element with the name "User", I would not return the login input. In that case, then I first searched for the form with the ID oWebBrowser.Document.GetElementById("frmLogin") . Then I searched for the user name control within the form found form.GetElementsByTagName("input").GetElementsByName("user")[0] . The same idea was made for the password.

    Applying the code below, the login attempt is made, but obviously, I do not have a valid username and password. Please see if you can solve it with these tips.

                oWebBrowser.ScriptErrorsSuppressed = true;
                oWebBrowser.Navigate("gsmfans.org/index.php?action=login");
    
                //https://stackoverflow.com/questions/583897/c-sharp-how-to-wait-for-a-webpage-to-finish-loading-before-continuing
                while (oWebBrowser.ReadyState != WebBrowserReadyState.Complete &&
                    oWebBrowser.Document == null)
                {
                    Application.DoEvents();
                }
    
                //https://stackoverflow.com/questions/9925022/webbrowser-document-is-always-null
                MessageBox.Show(oWebBrowser.Document.Url.AbsoluteUri);
    
                HtmlElement form = oWebBrowser.Document.GetElementById("frmLogin");
    
                HtmlElement userInput = form.GetElementsByTagName("input").GetElementsByName("user")[0];
                if (userInput != null)
                {  //tentativa de setar o subject
                    userInput.SetAttribute("value", "TesteUser");
                    userInput.ScrollIntoView(true);
                    MessageBox.Show("user");
                }
    
                HtmlElement passwordInput = form.GetElementsByTagName("input").GetElementsByName("passwrd")[0];
                if (passwordInput != null)
                { //tentativa de setar o message
                    passwordInput.SetAttribute("value", "TestePass");
                    MessageBox.Show("password");
                }
    
                if (form != null)
                { //tentativa de setar o message
                    form.InvokeMember("submit");
                    MessageBox.Show("submit");
                }
    
                while (oWebBrowser.ReadyState != WebBrowserReadyState.Complete &&
                    oWebBrowser.ReadyState != WebBrowserReadyState.Complete)
                {
                    Application.DoEvents();
                }
    
        
    26.01.2016 / 03:08