获取WPF WebBrowser HTML
我正在使用Wpf WebBrowser访问某个页面。 我需要得到它的HTML内容 – 我不能使用Webclient或WebReques等因为我需要在那些页面上执行JS。 我也尝试过Awesomium和Wf WebBrowser(都错了)。
dynamic doc=browser.Document; var text=doc.InnerHtml//or something like this
上面的代码对我不起作用,它显示无引用。 谁能告诉我怎么去取它? 我已经搜索了好几个星期,但没有发现任何真正有用的东西:/。 请回答一下你能想象到的最大笨蛋:D。 有时我会发现人们发给我一段代码而我不知道如何使用它…我的意思是请让你的post像结束一样
string HTML=some_stuff;
或者,如果你知道一些没有错误的替代浏览器,我可以访问HTML或者什么东西,让我在加载的Html上执行JS,像cookies一样影响和HTML源代码的变化,这也是一个非常好的答案。 我会感激任何帮助。
我曾经做过这样的事。 这太可怕了,但确实有效。
您需要添加对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() .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, , ); HtmlDocumentHelper.FillField(webBrowser.Document, , ); HtmlDocumentHelper.ClickButton(webBrowser.Document, ); HtmlDocumentHelper.ExecuteScript(webBrowser.Document, "alert(1);");
Yeeeaaaah! 我做的。 这很简单:
string HTML = (browser.Document as mshtml.IHTMLDocument2).body.outerHTML;
您是否尝试过名为InvokeScript()的wpf WebBrowser方法?
https://msdn.microsoft.com/en-us/library/cc491132(v=vs.110).aspx
string HTML = webBrowser.InvokeScript(@"document.getElementsByTagName ('html')[0].innerHTML").ToString();
当我尝试@Gray或@ czubehead时,代码body
始终为null。 但是,以下代码对我有用:
dynamic webBrowserDocument = webBrowser.Document; string html = webBrowserDocument?.documentElement?.InnerHtml;
并确保这应该进入LoadCompleted
或更高版本。 在Navigated
使用它时,源不完整甚至为null
。
上述就是C#学习教程:获取WPF WebBrowser HTML分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1016070.html