How can I use WebBrowser in web forms asp.net c #?

1

I'm trying to use WebBrowser in ASP.NET C # My question and log on to a site 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);
            }


        }



    }
}
    
asked by anonymous 20.09.2016 / 03:13

1 answer

0

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

But generally in my solutions I do the following:

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 log into a website.

As you can see the elements TXT_CPFCGC , TXT_SENHA , imageField , is the structure of the site I'm logging in to.

In the waitTillLoad method I use the speed, therefore, there are some sites that are slower to respond, and others are faster.

For more details see: link

link

    
21.09.2016 / 13:58