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

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()[0]).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,如下:

    ChromWebBrowser = new CefSharp.WinForms.ChromiumWebBrowser(url);
    ChromWebBrowser.FrameLoadEnd += ChromWebBrowser_FrameLoadEnd;

 

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();
复制代码

 

 

出处:https://www.cnblogs.com/leiyongbo/p/10484791.html

posted on 2021-10-22 15:36  jack_Meng  阅读(1756)  评论(0编辑  收藏  举报

导航