Manipulate page with Webbrowser

Asked

Viewed 4,347 times

2

I’m having trouble sending values to a form via Web Browser. My goal is to make a post, IE, send the values to inputsof the form and do the submit from the same, after this 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 executing it does not display any MessageBox and opens my browser on the page defined in Web Browser (meulink - to which has the form). Can anyone give me a help? I don’t know how to do this right, I’m basing myself on research.

  • that address meulink It’s some page, like www.google.com or is it a page of your application? It can be accessed without your system?

  • It’s a regular forum page made up of php, can be accessed without my system. It would be a login screen and another post screen of a forum and this system will only be to streamline the posts.

1 answer

4


The method WebBrowser.Navigate load the page in an asynchronous way, in order for you to manipulate the document you should expect the document to have been loaded.

You can do it two ways:

  1. Scheduling the event WebBrowser.DocumentCompleted (Solution cited in this post)
  2. Place the code below to ensure that the code does not proceed until the page has been loaded (This should be done after the method Navigate and after the call form.InvokeMember("submit");) (Solution cited 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 does a search for a keyword). I created a simple Windows application with a form, a Webbrowser component (which names the Windows application as you) and a button. All the code runs at the click of the button, which is below:

        private void button1_Click(object sender, EventArgs e)
        {
            //Resposta a pergunta /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 might have a problem selecting the control correctly. I applied the same solution idea above to the login page you mentioned and I really had to take care to find the controls and set the values.

Tips for you: If I searched for an element with the name "User", I would not return the login input. In this case then I first searched the form by Id oWebBrowser.Document.GetElementById("frmLogin"). After I searched the user name control inside the find form 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 user and password. See, please, if you can solve 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();
            }
  • I tested by copying and pasting your code and it worked, adapted to the forum and inputs and could not, initially with this page to login: http://www.gsmfans.org/index.php?action=login and this to post: http://www.gsmfans.org/index.php?action=post;board=1304.0; no error is displayed, nor MessageBox on the screen (until when I put else no not null)

  • I did Edit1 applying a code that locates and tries to log in to the page you quoted. I had to look for the control with more criteria, as explained. Besides, the page you mentioned never reached the state of complete WebBrowserReadyState.Complete, I also made adjustments to this. See if this solves your problem

  • Thanks, it worked perfectly was making a mistake when trying to catch the element by name, in the surveys was just like in the question rs.. The reward I can only activate in 2 hours. Thanks bro

  • Beauty! When you can, pass the reward because I’m starting now to help the gang around here and will give me more options to interact.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.