UWP获取任意网页加载完成后的HTML
主要思想:通过后台WebView载入指定网页,再提取出WebView中的内容
关键代码:
var html = await webView.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
有一个很简单的思路,
订阅WebView NavigationCompleted事件,然后让Navigate到指定的网址,发生事件时执行这行代码
除此之外,这里还有一个异步的方法,用到了TaskCompletionSource这个东西
首先,创建一个TaskCompletionSource:
TaskCompletionSource<string> completionSource = new TaskCompletionSource<string>();
因为返回的东西是string(html),所以泛型T设置成string
然后使用lambda的形式订阅Navigation事件:
webView.NavigationCompleted += async (sender, args) =>
{
if (args.Uri != uri)
return;
await Task.Delay();
var html = await sender.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
webView.NavigateToString("");
webView = null;
completionSource.SetResult(html);
};
Line5的延迟200ms,是为了Navigation完成之后再给页面里的其他一些元素(比如一些js脚本)一些加载的时间(讲道理订阅事件里也应该写一个的)
Line7的导航到空是为了防止WebView里的东西继续运行从而导致一些灵异事件(尤其是一些带视频的网页,咳咳)
Line9,给Task设置个Result,await就会结束
最后:
return completionSource.Task;
封装成类:
public class WebHelper
{
public class WebLoadedArgs:EventArgs
{
public bool Success { get; private set; }
public WebErrorStatus WebErrorStatus { get; private set; }
public string Html { get; private set; } public WebLoadedArgs(WebErrorStatus webErrorStatus)
{
WebErrorStatus = webErrorStatus;
Success = false;
} public WebLoadedArgs(string Html,WebErrorStatus webErrorStatus)
{
this.Html = Html;
WebErrorStatus = webErrorStatus;
Success = true;
}
} public string Url { get; private set; }
public event EventHandler<WebLoadedArgs> WebLoaded;
private WebView webView; public WebHelper(string Url)
{
this.Url = Url;
webView = new WebView(WebViewExecutionMode.SeparateThread);
webView.Navigate(new Uri(Url));
webView.NavigationCompleted += WebView_NavigationCompleted;
webView.NavigationFailed += WebView_NavigationFailed;
} private void WebView_NavigationFailed(object sender, WebViewNavigationFailedEventArgs e)
{
WebLoaded(this, new WebLoadedArgs(e.WebErrorStatus));
} private async void WebView_NavigationCompleted(WebView sender, WebViewNavigationCompletedEventArgs args)
{ var html = await sender.InvokeScriptAsync("eval", new string[] { "document.documentElement.outerHTML;" });
webView = null;
WebLoaded(this, new WebLoadedArgs(html,args.WebErrorStatus));
} /// <summary>
/// 异步实现获取Web内容
/// </summary>
/// <param name="Url">网址</param>
/// <param name="TimeOut">超时时间</param>
/// <returns>Web的Html内容</returns>
public static Task<string> LoadWebAsync(string Url,int Timeout)
{
return LoadWebAsync(Url, "", Timeout);
} /// <summary>
/// 异步实现获取Web内容
/// </summary>
/// <param name="Url">网址</param>
/// <param name="Referer">Header[Referer],用以解决一些盗链效验</param>
/// <param name="TimeOut">超时时间</param>
/// <returns>Web的Html内容</returns>
public static Task<string> LoadWebAsync(string Url,string Referer, int TimeOut)
{ WebView webView = new WebView(WebViewExecutionMode.SeparateThread);
Uri uri = new Uri(Url);
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, uri);
requestMessage.Headers.Add("Referer", Referer);
webView.NavigateWithHttpRequestMessage(requestMessage); TaskCompletionSource<string> completionSource = new TaskCompletionSource<string>();
webView.NavigationCompleted += async (sender, args) =>
{
if (args.Uri != uri)
return;
await Task.Delay();
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 = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(TimeOut);
timer.Tick += (sender, args) =>
{
timer = null;
webView.NavigateToString("");
webView = null;
completionSource.SetException(new TimeoutException());
};
timer.Start(); return completionSource.Task;
}
}
使用方法:
(事件订阅的方式)
WebHelper webHelper = new WebHelper("http://www.baidu.com/");
webHelper.WebLoaded += WebHelper_WebLoaded;
private void WebHelper_WebLoaded(object sender, WebHelper.WebLoadedArgs e)
{
if(e.Success)
{
var html = e.Html;
}
}
(异步的方式)
var html = await WebHelper.LoadWebAsync("http://www.baidu.com", );
UWP获取任意网页加载完成后的HTML的更多相关文章
- js判断图片加载完成后获取图片实际宽高
通常,我们会用jq的.width()/.height()方法获取图片的宽度/高度或者用js的.offsetwidth/.offsetheight方法来获取图片的宽度/高度,但这些方法在我们通过样式设置 ...
- Web前端性能优化总结——如何提高网页加载速度
一.提高网页加载速度的必要性 国际知名的一组来自Jupiter Research的数据显示:购物者在访问网站过程中的不满会导致销售损失和品牌受损,其中 77%的人将不再访问网站 ,62%的人不再从该网 ...
- 《转》如何让你的网页加载时间降低到 1s 内
当初分析了定宽高值和定宽高比这两种常见的图片延迟加载场景,也介绍了他们的应对方案,还做了一点技术选型的工作. 经过一段时间的项目实践,在先前方案的基础上又做了很多深入的优化工作.最终将好奇心日报的网页 ...
- 使用WebView监控网页加载状况,PerformanceMonitor,WebViewClient生命周期
原理:WebView加载Url完成后,注入js脚本,脚本代码使用W3C的PerformanceTimingAPI, 往js脚本传入一个Android对象(代码中为AndroidObject),在js脚 ...
- 如何让你的网页加载时间降低到 1s 内
当初分析了定宽高值和定宽高比这两种常见的图片延迟加载场景,也介绍了他们的应对方案,还做了一点技术选型的工作. 经过一段时间的项目实践,在先前方案的基础上又做了很多深入的优化工作.最终将好奇心日报的网页 ...
- iOS WKWebView添加网页加载进度条(转)
一.效果展示 WKWebProgressViewDemo.gif 二.主要步骤 1.添加UIProgressView属性 @property (nonatomic, strong) WKWebView ...
- 前端性能优化(四)——网页加载更快的N种方式
网站前端的用户体验,决定了用户是否想要继续使用网站以及网站的其他功能,网站的用户体验佳,可留住更多的用户.除此之外,前端优化得好,还可以为企业节约成本.那么我们应该如何对我们前端的页面进行性能优化呢? ...
- 浅析用Base64编码的图片优化网页加载速度
想必大家都知道网页加载的过程,从开始请求,到加载页面,开始解析和显示网页,遇到图片就再次向服务器发送请求,加载图片.如果图片很多的话,就会产生大量的http请求,从而影响页面的加载速度.所以现在有一种 ...
- Webbrowser控件判断网页加载完毕的简单方法 (转)
摘自:http://blog.csdn.net/cometnet/article/details/5261192 一般情况下,当ReadyState属性变成READYSTATE_COMPLETE时,W ...
随机推荐
- Js获取或计算时间的相关操作
//获取当前日期(年月日),如:2017-12-18 function getNowDate() { var dd = new Date(); var y = dd.getFullYear(); // ...
- HBase Region的定位
- Spring Http Basic(基本)和Digest(摘要)验证
Basic(基本)和Digest(摘要)验证都是web应用中很受欢迎的可选机制. Basic验证一般用来处理无状态的客户端,它们在每次请求都附带它们的证书. 很常见的用法是把它和基于表单的验证一起使用 ...
- Linux 命令之head, tail, tr, sort, uniq, grep
head [filename] head -n 11 [filename] -> First 11 lines head -c 20 [filename] -> First 20 char ...
- JavaScript对象继承方式
一.对象冒充 其原理如下:构造函数使用 this 关键字给所有属性和方法赋值(即采用类声明的构造函数方式).因为构造函数只是一个函数,所以可使 Parent 构造函数 成为 Children 的方法, ...
- Hibernate-HQL-Criteria-查询优化
1 查询总结 oid查询-get 对象属性导航查询 HQL Criteria 原生SQL 2 查询-HQL语法 2.1 基础语法 2.2 进阶语法 排序 条件 分页 聚合 投影 多表查询 SQL HQ ...
- 使用powerDesigner绘制类图
使用powerDesigner绘制类图 因为后面要理清楚spring中类与类之间关系,我们来看看如何使用powerDesigner绘制类图 你要去下载powerDesiger,一路下一步安装好 打开, ...
- TensorFlow的安装 (python3.6在有pip的条件下如何安装TensorFlow)
1.Window,MacOS,Linux都已支持Tensorflow. 2.Window用户只能使用python3.5(64bit).MacOS,Linux支持python2.7和python ...
- 在rabbitmq操作页面上添加队列、交换器及绑定示图
1.添加队列 2.添加交换器 3.绑定
- Qt运行不出现界面
安装Qt之后按照例程运行,结果不出现界面,原因是路径中有中文,将中文全部改成英文之后,问题解决.