Infernus
Infernus

Reputation: 53

Get source of Webpage in Webbrowser C#

Currently I have a website loaded in a WebBrowser component, which keeps changing stuff inside a certain <a> inside the page. In order for me to get the data, I have to create another WebRequest each 5 seconds, just to refresh the data (I think they're called dynamic pages). I've tried fetching the data from the WebBrowser (WebBrowser.DocumentText), but the value just remained the same, even though I am pretty sure it changed, because I can see it changed. I think the webrequest each 5 seconds takes up unnecesary memory space, and that this can be done easier.

Do you guys maybe know a way for me to do this?

Upvotes: 1

Views: 8613

Answers (2)

Hans Passant
Hans Passant

Reputation: 941217

Guessing at Winforms. You'll want to use the Document property to read back the DOM. Here's an example. Start a new Winforms project and drop a WebBrowser on the form. Then a label and a timer. Make the code look like this:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        webBrowser1.Url = new Uri("http://stackoverflow.com/questions/10781011/get-source-of-webpage-in-webbrowser-c-sharp");
        webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;
        timer1.Interval = 100;
        timer1.Tick += new EventHandler(timer1_Tick);
    }

    void timer1_Tick(object sender, EventArgs e) {
        var elem = webBrowser1.Document.GetElementById("wmd-input");
        label1.Text = elem.InnerText;
    }

    void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
        timer1.Enabled = true;
    }
}

The browser will navigate to your question. Type something in the Answer box, note how the label displays what you typed.

You'll need to tweak this code to work with your specific web page, alter the "wmd-input" element name. Use a DOM inspection tool to find the name. I like Firebug.

Upvotes: 2

MartinHN
MartinHN

Reputation: 19772

You could try to get the source via JavaScript.

Use the InvokeScript method to execute return document.documentElement.outerHTML;

This will return an Object which you should be able to type cast to a String.

Upvotes: 0

Related Questions