获取WPF WebBrowser的HTML

5
我正在使用Wpf WebBrowser访问某个页面。我需要获取它的HTML内容- 我不能使用Webclient或WebReques等,因为我需要在该页面上执行JS。我还尝试了Awesomium和Wf WebBrowser(都不正确)。
    dynamic doc=browser.Document;
    var text=doc.InnerHtml//or something like this

上面的代码对我不起作用,它显示空引用。有人能告诉我如何获取它吗?我已经搜索了几周,没有找到真正有效的东西 :/。有时候人们会给我发送一段代码,我不知道如何使用它...我的意思是请尽可能以最简单易懂的方式回答。请像对待一个最蠢的人一样回答 :D。

     string HTML=some_stuff;

如果您知道某些不会出现错误的替代浏览器,并且可以访问HTML或类似的东西,能够允许我执行JS并具有像Cookie和HTML源更改之类的影响,那么这也是一个非常好的答案。 对于任何帮助,我都会非常感激。
4个回答

11

耶!我做到了。这真的很简单:

    string HTML = (browser.Document as mshtml.IHTMLDocument2).body.outerHTML;

9
我曾经做过类似的东西。它很糟糕,但是它能工作。
你需要添加对 Microsoft.mshtml 的引用。
然后你可以使用 IHTMLDocument2。为什么是2?好问题……无论如何,我编写了几个类似这样的辅助函数:
public static void FillField(object doc, string id, string value)
{
    var element = findElementByID(doc, id);
    element.setAttribute("value", value);
}

public static void ClickButton(object doc, string id)
{
    var element = findElementByID(doc, id);
    element.click();
}

private static IHTMLElement findElementByID(object doc, string id)
{
    IHTMLDocument2 thisDoc;
    if (!(doc is IHTMLDocument2))
        return null;
    else
        thisDoc = (IHTMLDocument2)doc;

    var element = thisDoc.all.OfType<IHTMLElement>()
        .Where(n => n != null && n.id != null)
        .Where(e => e.id == id).First();
    return element;
}

JS的执行

private static void ExecuteScript(object doc, string js)
{
    IHTMLDocument2 thisDoc;
    if (!(doc is IHTMLDocument2))
        return;
    else
        thisDoc = (IHTMLDocument2)doc;
    thisDoc.parentWindow.execScript(js);
}

我称呼它们为这个......
HtmlDocumentHelper.FillField(webBrowser.Document, <id>, <value>);
HtmlDocumentHelper.FillField(webBrowser.Document, <id>, <value>);
HtmlDocumentHelper.ClickButton(webBrowser.Document, <id>);
HtmlDocumentHelper.ExecuteScript(webBrowser.Document, "alert(1);");

谢谢你提供的mshtml和IHTMLDocument2! - czubehead
哈,很高兴能帮到你!祝你好运。 - Gray

1

当我尝试使用@Gray或@czubehead的代码时,body始终为空。但是,以下代码对我有效:

dynamic webBrowserDocument = webBrowser.Document;
string html = webBrowserDocument?.documentElement?.InnerHtml;

请确保将此代码放置在LoadCompleted或更晚的位置。如果在Navigated中使用,源代码可能不完整甚至为null

-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接