C#使用CefSharp控件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#使用CefSharp控件

springsnow   2022-06-18 我要评论

一、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 

安装

使用Nuget包引用

把项目改成64位

切换到X64

安装完之后工具栏应该会多出来这个控件(直接拖动用不了!)

二、使用

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

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());
}

效果

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

到此这篇关于C#使用CefSharp控件实现爬虫的文章就介绍到这了。希望对大家的学习有所帮助,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们