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