C#爬蟲(02):Web browser控件CefSharp的使用


一、CefSharp介紹

CEF 全稱是Chromium Embedded Framework(Chromium嵌入式框架),是個基於Google Chromium項目的開源Web browser控件,支持Windows, Linux, Mac平台。CEFSharp就是CEF的C#移植版本。

就是一款.Net編寫的瀏覽器包,方便你在Winform和WPF中內嵌的Chrome瀏覽器組件

資源

GitHub地址:https://github.com/cefsharp/CefSharp
中文幫助文檔地址:https://github.com/cefsharp/CefSharp/wiki/CefSharp%E4%B8%AD%E6%96%87%E5%B8%AE%E5%8A%A9%E6%96%87%E6%A1%A3
CefSharp的WinForm樣例:https://github.com/cefsharp/CefSharp/tree/master/CefSharp.WinForms.Example
gitter交流討論區:https://gitter.im/cefsharp/CefSharp

1、安裝

使用Nuget包引用

image

image

3.把項目改成64位

image

image

切換到X64

image

安裝完之后工具欄應該會多出來這個控件(直接拖動用不了!)

image

二、使用

1、獲得頁面源代碼

注意:

1、GetSourceAsync獲取源碼的方法是異步操作

2、判斷頁面加載完成,會觸發FrameLoadEnd頁面加載完成事件。使用CEF無法確定一個網站是否已經完全加載完成,我們只能在它每一次加載完成時,處理它的頁面源碼。(如果需要主動等待網站加載完成,可以試試使用Selenium

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        ChromiumWebBrowser WebBrowser;

        private void Form1_Load(object sender, EventArgs e)
        {
            var settings = new CefSettings()
            {
                UserAgent = "Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Mobile Safari/537.36",
            };

            //Perform dependency check to make sure all relevant resources are in our output directory.
            Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);

            // cefsharp提供的瀏覽器控件,一般用它充滿窗口就搞定了
            WebBrowser = new ChromiumWebBrowser("http://www.163.com")
            {
                // 填充整個父控件
                Dock = DockStyle.Fill
            };
            WebBrowser.FrameLoadEnd += new EventHandler<FrameLoadEndEventArgs>(FrameEndFunc);

            // 添加到窗口的控件列表中
            this.panel1.Controls.Add(WebBrowser);

        }
        private void FrameEndFunc(object sender, FrameLoadEndEventArgs e)
        {
            MessageBox.Show("加載完畢");
            this.BeginInvoke(new Action(() =>
            {
                String html = WebBrowser.GetSourceAsync().Result;
                richTextBox1.Text = html;
            }));
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 結束時要銷毀
            Cef.Shutdown();
        }
    }
}

效果:可以加載很多原生webbrowser不能加載的內容 可以適應iframe

image

2、執行頁面中的js函數

測試的js代碼

<html>
<body>
<button type="button" onclick="test(1,2)">測試按鈕</button>
</body>
<script type="text/javascript">
function test(a,b)
{
   var c = testfunc(a,b);
   alert(c);
}
function testfunc(a,b)
{
    return a+b;
}

</script>
<html>

調用頁面中的testfunc函數

private void button3_Click(object sender, EventArgs e)
{
    using (StreamReader sr = new StreamReader("JavaScript1.html"))
    {
        string html = sr.ReadToEnd();
        WebBrowser.LoadHtml(html, "http://testpage/");
    }
}

private void button4_Click(object sender, EventArgs e)
{
    String script = "testfunc(99,1)";
    var result = this.WebBrowser.EvaluateScriptAsync(script).Result.Result;
    MessageBox.Show(result.ToString());
}

效果

image

3、常用方法

//瀏覽網址:
WebBrowser = new ChromiumWebBrowser("https://www.baidu.com");
//
WebBrowser.Load("https://www.baidu.com");

// 獲取HTML(整體): 
WebBrowser.GetSourceAsync().Result;

 // 獲取HTML(特定Frame):
 WebBrowser.GetBrowser().GetFrame(“SI2_mem_index”).GetSourceAsync().Result;

//執行網頁上的JavaScript:
 ExecuteJavaScriptAsync("document.getElementById('username').onkeydown();");

 //模擬左鍵點擊:
 WebBrowser.GetBrowser().GetHost().SendMouseClickEvent(x, y, MouseButtonType.Left, false, 1, CefEventFlags.None);
 Thread.Sleep(50);
 WebBrowser.GetBrowser().GetHost().SendMouseClickEvent(x, y, MouseButtonType.Left, true, 1, CefEventFlags.None);

學習實例地址:https://github.com/zhaotianff/CSharpCrawler


免責聲明!

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



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