Is it possible to use Webbrowser on the web Forms Asp.net c#?

Asked

Viewed 557 times

1

I’m looking to use Webbrowser on Asp.net C# My question and log into a website using it

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;

namespace WebFormulario01
{
    public partial class WebForm : System.Web.UI.Page
    {
        WebBrowser browser;
  

        protected void Page_Load(object sender, EventArgs e)
        {
            //http://www.macoratti.net/15/08/vbn_wblg1.htm 
        }

        protected void btnIrPara_Click(object sender, EventArgs e)
        {
            try
            {
                browser = new WebBrowser();
                browser.Navigate("http://sportone.sisguardiao.com.br/");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro : " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        protected void btnLogar_Click(object sender, EventArgs e)
        {

            try
            {
            //pega o name
            browser.Document.GetElementById("LOGIN").SetAttribute("value", txtLogin.Text);
            browser.Document.GetElementById("SENHA").SetAttribute("value", txtSenha.Text);
            browser.Document.GetElementById("opcao").InvokeMember("click");
            }
            catch (Exception ex)
            {
                MessageBox.Show("Erro : " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }


        }



    }
}

1 answer

0

For you to log into a website using WebBrowser, will depend a lot on how is the structure of the site, how are arranged the elements you should insert values in them.

But usually in my solutions I do as follows:

public enum VelocidadeExecucao
{
    rapida = 100000,
    normal = 300000,
    lenta = 500000
}

public readonly int _velocidade = VelocidadeExecucao.normal;


private void IniciarExecução
{
    browser = new WebBrowser();
    browser.Navigate("http://sportone.sisguardiao.com.br/");

    waitTillLoad(browser, _velocidade);
    InjectAlertBlocker(webBrowser);

    var logado = Logar("Login", "senha", browser);

    if (logado)
    {
            //Continua a execução depois do site logado
    }
}

//Espera até que o site termine de carrega a requisição
public void waitTillLoad(WebBrowser webBrControl, int _velocidade = _velocidade)
{
    WebBrowserReadyState loadStatus;

    //wait till beginning of loading next page 

    var waittime = _velocidade;

    var counter = 0;

    while (true)
    {
        loadStatus = webBrControl.ReadyState;

        Application.DoEvents();

        if ((counter > waittime) || (loadStatus == WebBrowserReadyState.Uninitialized) ||
        (loadStatus == WebBrowserReadyState.Loading) || (loadStatus == WebBrowserReadyState.Interactive))
            break;
        counter++;
    }

    //wait till the page get loaded.

    counter = 0;

    while (true)
    {
        loadStatus = webBrControl.ReadyState;

        Application.DoEvents();

        if (loadStatus == WebBrowserReadyState.Complete && webBrControl.IsBusy != true)
            break;

        counter++;
    }

}

//Remove o alert do javascript
public void InjectAlertBlocker(WebBrowser webBrowser1)
{
    if (webBrowser1.ReadyState != WebBrowserReadyState.Complete) return;
    HtmlElement body = webBrowser1.Document.GetElementsByTagName("body")[0];
    HtmlElement DivEl = webBrowser1.Document.CreateElement("div");
    DivEl.SetAttribute("id", "msgHMB");
    IHTMLDivElement divElement = (IHTMLDivElement)DivEl.DomElement;
    body.AppendChild(DivEl);

    HtmlElement head = webBrowser1.Document.GetElementsByTagName("head")[0];
    HtmlElement scriptEl = webBrowser1.Document.CreateElement("script");
    IHTMLScriptElement element = (IHTMLScriptElement)scriptEl.DomElement;
    string alertBlocker = "window.alert = function (txt) { document.cookie = 'alertErro= '+txt+'; ' }";
    element.text = alertBlocker;
    head.AppendChild(scriptEl);
}

public bool Logar(string login, string senha, WebBrowser webBrowser)
{
        var result = false;
        try
        {
            var doc = webBrowser.Document;

            if (doc != null)
            {
                var txtUsuario = doc.All.GetElementsByName("TXT_CPFCGC")[0];

                // vamos obter a caixa de texto - neste caso a primeira caixa de texto
                var txtSenha = doc.All.GetElementsByName("TXT_SENHA")[0];

                var btnEntra = doc.All.GetElementsByName("imageField")[0];

                txtUsuario.SetAttribute("value", login);

                txtSenha.SetAttribute("value", senha);

                InjectAlertBlocker(webBrowser);

                btnEntra.InvokeMember("click");

                waitTillLoad(webBrowser);
            }
            doc = webBrowser.Document;                
            //Caso não existe mais o componente de login mais da página, é porque esta logado
            if (doc != null && doc.All.GetElementsByName("TXT_CPFCGC").Count == 0)
            {
                result = true;
            }
        }
        catch (Exception)
        {
            // ignored
        }

        return result;
}

This is one of the ways I have in my Robot to login to a site.

How can you perceive the elements TXT_CPFCGC, TXT_SENHA, imageField, is the structure of the site I’m logging in to.

In the method waitTillLoad I use the speed because, have some sites that are more time consuming to respond, and others faster.

For more details see: https://msdn.microsoft.com/pt-br/library/system.windows.forms.webbrowser(v=vs.110). aspx

https://msdn.microsoft.com/en-us/library/w6t65c4y(v=vs.110). aspx

Browser other questions tagged

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