public classWebHelper
{public classWebLoadedArgs:EventArgs
{public bool Success { get; private set; }public WebErrorStatus WebErrorStatus { get; private set; }public string Html { get; private set; }publicWebLoadedArgs(WebErrorStatus webErrorStatus)
{
WebErrorStatus=webErrorStatus;
Success= false;
}public WebLoadedArgs(stringHtml,WebErrorStatus webErrorStatus)
{this.Html =Html;
WebErrorStatus=webErrorStatus;
Success= true;
}
}public string Url { get; private set; }public event EventHandlerWebLoaded;privateWebView webView;public WebHelper(stringUrl)
{this.Url =Url;
webView= newWebView(WebViewExecutionMode.SeparateThread);
webView.Navigate(newUri(Url));
webView.NavigationCompleted+=WebView_NavigationCompleted;
webView.NavigationFailed+=WebView_NavigationFailed;
}private void WebView_NavigationFailed(objectsender, WebViewNavigationFailedEventArgs e)
{
WebLoaded(this, newWebLoadedArgs(e.WebErrorStatus));
}private async voidWebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{var html = await sender.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;"});
webView= null;
WebLoaded(this, newWebLoadedArgs(html,args.WebErrorStatus));
}///
///异步实现获取Web内容///
/// 网址
/// 超时时间
/// Web的Html内容
public static Task LoadWebAsync(string Url,intTimeout)
{return LoadWebAsync(Url, "", Timeout);
}///
///异步实现获取Web内容///
/// 网址
/// Header[Referer],用以解决一些盗链效验
/// 超时时间
/// Web的Html内容
public static Task LoadWebAsync(string Url,string Referer, intTimeOut)
{
WebView webView= newWebView(WebViewExecutionMode.SeparateThread);
Uri uri= newUri(Url);
HttpRequestMessage requestMessage= newHttpRequestMessage(HttpMethod.Get, uri);
requestMessage.Headers.Add("Referer", Referer);
webView.NavigateWithHttpRequestMessage(requestMessage);
TaskCompletionSource completionSource = new TaskCompletionSource();
webView.NavigationCompleted+= async (sender, args) =>{if (args.Uri !=uri)return;await Task.Delay(200);var html = await sender.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;"});
webView.NavigateToString("");
webView= null;
completionSource.SetResult(html);
};
webView.NavigationFailed+= (sender, args) =>{
webView= null;
completionSource.SetException(new WebException("", (WebExceptionStatus)args.WebErrorStatus));
};
DispatcherTimer timer= newDispatcherTimer();
timer.Interval=TimeSpan.FromSeconds(TimeOut);
timer.Tick+= (sender, args) =>{
timer= null;
webView.NavigateToString("");
webView= null;
completionSource.SetException(newTimeoutException());
};
timer.Start();returncompletionSource.Task;
}
}