using CefSharp; using CefSharp.WinForms; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using HT=HtmlAgilityPack; namespace CefSharpGetHtml { public partial class Form1 : Form { public string url { get; private set; } public string path { get; private set; } ChromiumWebBrowser webBrowser = null; public Form1(string[] args) { InitializeComponent(); url=args[0]; } private async void web_Load(object sender, FrameLoadEndEventArgs e) { if (webBrowser != null && webBrowser.IsBrowserInitialized) { //调试 // webBrowser.GetBrowser().ShowDevTools(); var task1 = await webBrowser.GetSourceAsync(); // var task = webBrowser.EvaluateScriptAsync(@" // (function() { // return document.getElementsByTagName('html')[0].innerHTML; // })();"); // object result; // task.ContinueWith(t => // { // if (!t.IsFaulted) // { // var response = t.Result; // result = response.Success ? (response.Result ?? "null") : response.Message; // MessageBox.Show("得到的结果是: " + result); // } // else // { // MessageBox.Show("出错了"); // } // }, TaskContinuationOptions.PreferFairness); //} //try //{ // webBrowser.CloseDevTools(); // webBrowser.GetBrowser().CloseBrowser(true); //} //catch { } //try //{ // if (webBrowser != null) // { // webBrowser.Dispose(); // Cef.Shutdown(); // } //} //catch { } this.webBrowser.FrameLoadEnd += Last_Load; } } private void Form1_Load(object sender, EventArgs e) { string path = url; var setting = new CefSharp.CefSettings(); // setting.UserAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Version/10.0 Mobile/14F89 Safari/602.1"; setting.UserAgent = " Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.109 Safari/537.36"; CefSharp.Cef.Initialize(setting, true, false); webBrowser = new ChromiumWebBrowser(path); webBrowser.Dock = DockStyle.Fill;//填充方式 this.Controls.Add(webBrowser); this.webBrowser.FrameLoadEnd += web_Load; } private async void Last_Load(object sender, FrameLoadEndEventArgs e) { if (webBrowser != null && webBrowser.IsBrowserInitialized) { var task1 = await webBrowser.GetSourceAsync(); webBrowser.RequestHandler = new myrequesthandler(); System.IO.File.WriteAllText(@"d:\cefSharpWeiBo.html",task1,Encoding.UTF8); try { // webBrowser.CloseDevTools(); webBrowser.GetBrowser().CloseBrowser(true); } catch { } try { if (webBrowser != null) { webBrowser.Dispose(); Cef.Shutdown(); } } catch { } //HT.HtmlDocument doc = new HT.HtmlDocument(); // doc.LoadHtml(task1); // var node= doc.DocumentNode.SelectSingleNode("//div"); // Console.WriteLine(node.InnerText); } } } }