C#WebBrowser控件 – 在AJAX之后获取文档元素?

我正在编写一个使用WebBrowser控件的应用程序来查看可以通过添加新内容/元素的AJAX更改的Web内容。 我似乎无法以任何方式尝试新元素。 BrowserCtl.DocumentText没有最新的页面,当然它也不在“查看源代码”中。

有没有办法使用此控件获取此新数据? :(请帮忙。谢谢!

IE:

Browser.Navigate("www.somewebpagewithAJAX.com"); //Code that waits for browser to finish... ... //WebBrowser control has loaded content and AJAX has loaded new content // (is visible at runtime on form) but can't see them in Browser.Document.All // or Browser.DocumentText :( 

我为我解决了这个问题。

关键是,为通过ajax调用填充的div元素的onPropertyChanged事件附加一个处理程序。

 HtmlElement target = webBrowser.Document.GetElementById("div_populated_by_ajax"); if (target != null) { target.AttachEventHandler("onpropertychange", handler); } 

最后,

 private void handler(Object sender, EventArgs e) { HtmlElement div = webBrowser.Document.GetElementById("div_populated_by_ajax"); if (div == null) return; String contentLoaded = div.InnerHtml; // get the content loaded via ajax } 
 using System; using System.Windows.Forms; namespace WebBrowserDemo { class Program { public const string TestUrl = "http://www.w3schools.com/Ajax/tryit_view.asp?filename=tryajax_first"; [STAThread] static void Main(string[] args) { WebBrowser wb = new WebBrowser(); wb.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(wb_DocumentCompleted); wb.Navigate(TestUrl); while (wb.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); } Console.WriteLine("\nPress any key to continue..."); Console.ReadKey(true); } static void wb_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { WebBrowser wb = (WebBrowser)sender; HtmlElement document = wb.Document.GetElementsByTagName("html")[0]; HtmlElement button = wb.Document.GetElementsByTagName("button")[0]; Console.WriteLine(document.OuterHtml + "\n"); button.InvokeMember("Click"); Console.WriteLine(document.OuterHtml); } } } 

您将需要使用DOM。 将WebBrowser.Document.DomDocument转换为IHTMLDocument?。 您必须导入一些COM接口或Microsoft.mshtml程序集。

有关详细信息,请访问http://msdn.microsoft.com/en-us/library/aa752641(VS.85).aspx 。

我假设您正在阅读从Ajax请求生成的内容,您需要用户将应用程序升级到加载相关数据的位置,此时您运行代码来读取数据。

如果不是这样,您将需要自动化此过程,生成点击事件,构建您有兴趣阅读的DOM节点。 我通常使用WebBrowser控件执行此操作,并倾向于在Javascript中编写该层function并使用.InvokeScript()调用它。 另一种方法是找到从C#触发Ajaxfunction的节点并手动触发它们的点击事件:

 HtmlElement content = webMain.Document.GetElementById("content"); content.RaiseEvent("onclick"); 

上面脚本中需要注意的一个重要方面是,如果您接受并解决HtmlElement对象类型的限制,您可以在C#中天真地与DOM节点交互。

如何运行javascript来标题元素并在新窗口中显示?

我没有测试过,但可能会有效。

 (WebBrowser)w.Navigate("javascript:GetElementById('div').innerHtml;", true); 

在新窗口中打开返回的true属性。 (或者框架或者你可以找到更好的方法)

要捕获NewWindow事件,您需要引用Windows / System32文件夹中的SHDocVw.dll。 然后你可以像这样强制转换WebBrowser控件:

 SHDocVw.WebBrowser_V1 browser = (SHDocVw.WebBrowser_V1)(WebBrowser)w.ActiveXInstance; 

存储响应后,您可以立即关闭它。 祝你好运,让我知道它是怎么回事。

你控制网页了吗?

如果是这样,这里有一篇博客文章解释如何: http : //www.palladiumconsulting.com/blog/sebastian/2007/04/ultimate-intranet-toy.html

如果没有,可能有一个解决方案,但我无法帮助你,抱歉。