CefSharp获取页面Html代码的两种方式

时间:2023-03-08 22:12:34

CefSharp在NuGet的简介是“The CefSharp Chromium-based browser component”,机翻的意思就是“基于Cefsharp Chromium的浏览器组件”

第一种方法 就是执行JavaScript代码获取当前html代码

StringBuilder sb = new StringBuilder();
sb.AppendLine("function tempFunction() {");
//sb.AppendLine(" return document.body.innerHTML; ");
sb.AppendLine(" return document.getElementsByTagName('html')[0].innerHTML; ");
sb.AppendLine("}");
sb.AppendLine("tempFunction();");
var task01 = browser.GetBrowser().GetFrame(browser.GetBrowser().GetFrameNames()[]).EvaluateScriptAsync(sb.ToString());
task01.ContinueWith(t =>
{
if (!t.IsFaulted)
{
var response = t.Result;
if (response.Success == true)
{
if (response.Result != null)
{
string resultStr = response.Result.ToString();
}
}
}
});

第二种方法 是利用CefSharp.IFrame.GetSourceAsync()方法

/// <summary>
/// 页面加载结束
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Browser_FrameLoadEnd(object sender, FrameLoadEndEventArgs e)
{
var task02 = e.Frame.GetSourceAsync();
task02.ContinueWith(t =>
{
if (!t.IsFaulted)
{
string resultStr = t.Result;
}
});
}

我这里是在Browser_FrameLoadEnd事件中直接获取的IFrame,

GetSourceAsync()方法我简单翻译了一下

        //
// 摘要:
// Retrieve this frame's HTML source as a string sent to the specified visitor.
// 检索此框架的HTML源代码以字符串形式发送给指定访问者。
//
// 返回结果:
// a System.Threading.Tasks.Task`1 that when executed returns this frame's HTML
// source as a string.
// 一个线程任务,执行时将此框架的HTML源文件作为字符串返回。
Task<string> GetSourceAsync();