zoukankan      html  css  js  c++  java
  • 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,

    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();
  • 相关阅读:
    [HAOI2008]糖果传递
    LGTB 与大数
    LGTB 与序列
    poj1160 Post Office
    组队
    [JLOI2015]装备购买
    三元组
    乘法表
    [BZOJ3730]震波
    [Luogu3345][ZJOI2015]幻想乡战略游戏
  • 原文地址:https://www.cnblogs.com/leiyongbo/p/10484791.html
Copyright © 2011-2022 走看看