uwp html5,UWP获取任意网页加载完成后的HTML

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;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值