Manipulate page with WebBrowser
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 the same, 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 set in the Web Browser
(meulink
- the one with the form). Can someone give me a help? I don't know how to do it right, I'm relying on research.
1 answers
The method WebBrowser.Navigate
loads the page asynchronously, for you to manipulate the document you must wait until the document has been loaded.
You can do this in two ways:
- scheduling the event
WebBrowser.DocumentCompleted
(solution cited in this post ) - put the code below to ensure that the code does not advance until the page has been loaded (this must be done after the
Navigate
method and after the callform.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 I named oWebBrowser just like you) and a button. All the code executes on the click of the button, 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 believe you must be having trouble selecting the control correctly. I applied the same solution idea above, on the login page you mentioned and actually had to take some care to find the controls and set the values.
Tips for you: if I searched for an element with the name "User", it would not return the login input. In this case then I first searched the form by Id oWebBrowser.Document.GetElementById("frmLogin")
. Then I searched for the user name control inside the found Form form.GetElementsByTagName("input").GetElementsByName("user")[0]
. The same idea was made for the password.
Applying the code below, it is made the login attempt, 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();
}