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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM