首页 文章

获取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或者什么东西,让我在加载的Html上执行JS,像cookies一样影响和HTML源代码的变化,这也是一个非常好的答案 . 我会感激任何帮助 .

4 回答

  • 8

    我曾经做过这样的事 . 这太可怕了,但确实有效 .

    您需要添加对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);");
    
  • 11

    Yeeeaaaah!我做的 . 这很简单:

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

    您是否尝试过名为InvokeScript()的wpf WebBrowser方法?

    http://msdn.microsoft.com/en-us/library/cc491132(v=vs.110).aspx

    string HTML = webBrowser.InvokeScript(@"document.getElementsByTagName ('html')[0].innerHTML").ToString();
    
  • 0

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

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

    并确保这应该进入 LoadCompleted 或更晚 . 在 Navigated 中使用此功能时,源不完整甚至 null .

相关问题