我想为Alexei的答案贡献一些代码。几点:
严格来说,不一定总能确定页面何时以100%的概率完成渲染。有些页面非常复杂,并使用连续的AJAX更新。但是,通过轮询页面的当前HTML快照以查找更改并检查
WebBrowser.IsBusy
属性,我们可以非常接近。这就是LoadDynamicPage
下面的内容。在页面上方永无休止的情况下,必须在上面加上一些超时逻辑(请注意
CancellationTokenSource
)。Async/await
是一个很好的编码工具,因为它为我们的异步轮询逻辑提供了线性代码流,从而大大简化了它。使用浏览器功能控件启用HTML5呈现非常重要,因为
WebBrowser
默认情况下,该功能以IE7仿真模式运行。这就是SetFeatureBrowserEmulation
下面的内容。这是一个WinForms应用程序,但是可以轻松地将该概念转换为控制台应用程序。
此逻辑在您专门提到的URL上很好用:https : //www.google.com/#q=where+am+i。
using Microsoft.Win32;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;namespace WbFetchPage
{
public partial class MainForm : Form
{
public MainForm()
{
SetFeatureBrowserEmulation();
InitializeComponent();
this.Load += MainForm_Load;
}// start the task async void MainForm_Load(object sender, EventArgs e) { try { var cts = new CancellationTokenSource(10000); // cancel in 10s var html = await LoadDynamicPage("https://www.google.com/#q=where+am+i", cts.Token); MessageBox.Show(html.Substring(0, 1024) + "..." ); // it's too long! } catch (Exception ex) { MessageBox.Show(ex.Message); } } // navigate and download async Task<string> LoadDynamicPage(string url, CancellationToken token) { // navigate and await documentCompleted var tcs = new TaskCompletionSource<bool>(); WebBrowserdocumentCompletedEventHandler handler = (s, arg) => tcs.TrySetResult(true); using (token.Register(() => tcs.TrySetCanceled(), useSynchronizationContext: true)) { this.webBrowser.documentCompleted += handler; try { this.webBrowser.Navigate(url); await tcs.Task; // wait for documentCompleted } finally { this.webBrowser.documentCompleted -= handler; } } // get the root element var documentElement = this.webBrowser.document.GetElementsByTagName("html")[0]; // poll the current HTML for changes asynchronosly var html = documentElement.OuterHtml; while (true) { // wait asynchronously, this will throw if cancellation requested await Task.Delay(500, token); // continue polling if the WebBrowser is still busy if (this.webBrowser.IsBusy) continue; var htmlNow = documentElement.OuterHtml; if (html == htmlNow) break; // no changes detected, end the poll loop html = htmlNow; } // consider the page fully rendered token.ThrowIfCancellationRequested(); return html; } // enable HTML5 (assuming we're running IE10+) // more info: https://stackoverflow.com/a/18333982/1768303 static void SetFeatureBrowserEmulation() { if (LicenseManager.UsageMode != LicenseUsageMode.Runtime) return; var appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName); Registry.SetValue(@"HKEY_CURRENT_USERSoftwareMicrosoftInternet ExplorerMainFeatureControlFEATURE_BROWSER_EMULATION", appName, 10000, RegistryValueKind.DWord); }}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)