Display portion of a Website into a Web Browser

2019-08-27 15:58发布

问题:

i want to navigate to a specific website, and i want then to be displayed in the web browser only a portion of the website, which starts with:

<div id="dex1" ...... </div>

I know i need to get the element by id, but firstly i tried writing this:

string data = webBorwser.Document.Body.OuterHtml;

So from data i need to grab that content "id" and display it and the rest to be deleted.

Any idea on this?

回答1:

webBrowser1.DocumentCompleted += (sender, e) =>
{
    webBrowser1.DocumentText = webBrowser1.Document.GetElementById("dex1").OuterHtml;
};

On second thoughts, don't do that, setting the DocumentText property causes the DocumentCompleted event to fire again. So maybe do:

webBrowser1.DocumentCompleted += webBrowser1_DocumentCompleted;

void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
    webBrowser1.DocumentCompleted -= webBrowser1_DocumentCompleted;
    webBrowser1.DocumentText = webBrowser1.Document.GetElementById("dex1").OuterHtml;
}

Although in most real world cases I'd expect you'd get better results injecting some javascript to do the DOM manipulation, a la Andrei's answer.

Edit: to just replace everything inside the body tag which might if you're lucky maintain all the required styling and scripts if they're all in the head don't reference any discarded context, you may have some joy with:

webBrowser1.Document.Body.InnerHtml = webBrowser1.Document.GetElementById("dex1").OuterHtml;


回答2:

So, as you probably need a lot of external resources like scripts and images. You can add some custom javascript to modify the DOM however you like after you have loaded the document from your website. From How to update DOM content inside WebBrowser Control in C#? it would look something like this:

HtmlElement headElement = webBrowser1.Document.GetElementsByTagName("head")[0];
HtmlElement scriptElement = webBrowser1.Document.CreateElement("script");
IHTMLScriptElement domScriptElement = (IHTMLScriptElement)scriptElement.DomElement;
domScriptElement.text = "function applyChanges(){ $('body >').hide(); $('#dex1').show().prependTo('body');}";
headElement.AppendChild(scriptElement);

// Call the nextline whenever you want to execute your code
webBrowser1.Document.InvokeScript("applyChanges");

This is also assuming that jquery is available so you can do simple DOM manipulation.

The javascript code is just hiding all children on the body and then prepending the '#dex' div to the body so that it's at the top and visible.