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

posted on 2020-06-10 19:04  springsnow  阅读(10414)  评论(1编辑  收藏  举报

导航