Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WebBrowser - empty DocumentText

Tags:

browser

c#

I'm trying to use WebBrowser class, but of course it doesn't work.

My code:

WebBrowser browser = new WebBrowser();
browser.Navigate("http://www.google.com");

while(browser.DocumentText == "")
{
    continue;
}
string html = browser.DocumentText;

browser.DocumentText is always "". Why?

like image 917
carck3r Avatar asked Feb 15 '26 06:02

carck3r


1 Answers

You should use DocumentCompleted event, and if you don't have WebForms application, also ApplicationContext might be needed.

static class Program
{
    [STAThread]
    static void Main()
    {
        Context ctx = new Context();
        Application.Run(ctx);

        // ctx.Html; -- your html
    }
}

class Context : ApplicationContext
{
    public string Html { get; set; }

    public Context()
    {
        WebBrowser browser = new WebBrowser();
        browser.AllowNavigation = true;
        browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);
        browser.Navigate("http://www.google.com");
    }

    void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        Html = ((WebBrowser)sender).DocumentText;
        this.ExitThread();
    }
}
like image 121
Krzysztof Avatar answered Feb 17 '26 20:02

Krzysztof