C# 使用CefSharp完成自动签到

1首先新建项目,右键项目选择管理NuGet 程序包,在浏览中搜索CefSharp.Winfrom ,点击安装,会自动安装相应的包。因为CefSharp是不能以AnyCPU的模式运行所以需要修改配置,有两种方式右键选择

(1) 右键解决方案选择配置管理器,把活动解决方案平台改成x86即可。

(2)打开app.config 文件添加配置 ,下边红色的字

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <probing privatePath="x86"/>
    </assemblyBinding>
  </runtime>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2" />
    </startup>
</configuration>

 点击项目,右键卸载项目 ,右键选择编辑XXXXX.csproj 添加红色字配置

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <Import Project="..\packages\CefSharp.WinForms.79.1.360\build\CefSharp.WinForms.props" Condition="Exists('..\packages\CefSharp.WinForms.79.1.360\build\CefSharp.WinForms.props')" />
  <Import Project="..\packages\CefSharp.Common.79.1.360\build\CefSharp.Common.props" Condition="Exists('..\packages\CefSharp.Common.79.1.360\build\CefSharp.Common.props')" />
  <Import Project="..\packages\cef.redist.x86.79.1.36\build\cef.redist.x86.props" Condition="Exists('..\packages\cef.redist.x86.79.1.36\build\cef.redist.x86.props')" />
  <Import Project="..\packages\cef.redist.x64.79.1.36\build\cef.redist.x64.props" Condition="Exists('..\packages\cef.redist.x64.79.1.36\build\cef.redist.x64.props')" />
  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
  <PropertyGroup>
    <CefSharpAnyCpuSupport>true</CefSharpAnyCpuSupport>
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
。。。。。。。。。。。。。。

完成基本配置

2 首先添加一个窗体Form1 添加如下控件

 后台代 #region 声明变        /// <summary>        /// 声明根目录的地址

/// </summary>
        string StrPath = AppDomain.CurrentDomain.BaseDirectory + "MobileData.xml";
        /// <summary>
        /// 实例化XML文档
        /// </summary>
        XmlDocument XmlDoc = new XmlDocument();
        /// <summary>
        /// 声明谷歌浏览器
        /// </summary>
        public ChromiumWebBrowser chromeBrowser;
        /// <summary>
        /// 创建一个线程
        /// </summary>
Thread childThread = new Thread(new ThreadStart(()=>{})); [System.Runtime.InteropServices.DllImport("user32")] private static extern IntPtr GetActiveWindow();//获取当前窗体的活动状态 // 判断当前窗口是否处于活动状态的方法 private bool ThisIsActive() { return (GetActiveWindow() == this.Handle); } int SuccessCount = 0; string userinfo = ""; #endregion #region 窗体初始化 public Form1() { InitializeComponent(); } /// <summary> /// 初始化浏览器以及用户数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_Load(object sender, EventArgs e) { var setting = new CefSettings(); // 设置语言 setting.Locale = "zh-CN"; //cef设置userAgent setting.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36"; //配置浏览器路径 setting.BrowserSubprocessPath = @"x86\CefSharp.BrowserSubprocess.exe"; Cef.Initialize(setting, performDependencyCheck: true, browserProcessHandler: null); chromeBrowser = new ChromiumWebBrowser("http://baidu.com"); panel1.Controls.Add(chromeBrowser); chromeBrowser.Dock = DockStyle.Fill; BindListBox(); } #endregion #region 创建线程调用签到方法 /// <summary> /// 创建工作线程 /// </summary> public void CreateWorkThread() { childThread = new Thread(new ThreadStart(SetAuto)); childThread.Start(); } #endregion #region 签到方法 public void SetAuto() { SuccessCount = 0; userinfo = ""; string user = ""; string js = ""; for (int i = 0; i < txt_Users.Items.Count; i++) { chromeBrowser.Load("http://baidu.com"); user = txt_Users.Items[i].ToString(); Thread.Sleep(3500); ExecuteJs(chromeBrowser, "网页中的js或者自己写的"); Thread.Sleep(3000); ExecuteJs(chromeBrowser, "网页中的js或者自己写的"); Thread.Sleep(1500); js = $"document.getElementsByName('文本框名称')[0].value = '{user.Split(':')[0]}';document.getElementsByName('文本框名称')[0].value = '{user.Split(':')[1]}'; "; ExecuteJs(chromeBrowser, js); Thread.Sleep(1500); js = "document.querySelector('[type=submit]').click();"; ExecuteJs(chromeBrowser, js); Thread.Sleep(3000); ExecuteJs(chromeBrowser, "网页中的js或者自己写的"); //执行js, Thread.Sleep(1500); if (chromeBrowser.Address == "www.baidu.com\ok")//判断是否已签到成功 { ExecuteJs(chromeBrowser, "网页中的js或者自己写的"); Thread.Sleep(2500); } js = @"document.getElementsByClassName('提交按钮')[0].click(); "; ExecuteJs(chromeBrowser, js); Thread.Sleep(3000); if (chromeBrowser.Address == "www.baidu.com\ok")//如果签到成功获取当前签到用户并记录个数和名称 { js = @"(function (){ return document.querySelectorAll('a')[0].innerHTML})(); "; chromeBrowser.EvaluateScriptAsync(js).ContinueWith(x => { var response = x.Result; if (response.Success && response.Result != null)//判断结果是否返回成功并且结果不为空 { userinfo += response.Result.ToString().Trim().Split('')[1].Substring(0, 3) + " ";//截取用户名 } }); SuccessCount += 1;//添加个数 } Thread.Sleep(1200); } if (SuccessCount != txt_Users.Items.Count) { CreateWorkThread(); } else { writeLog($"在{DateTime.Now}时,已自动签到{SuccessCount}个,用户:{userinfo}"); MessageBox.Show($"在{DateTime.Now}时,已自动签到{SuccessCount}个,用户:{userinfo}");
 childThread.Abort(); }
} /// <summary> /// 手动签到 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Btn_Auto_Click(object sender, EventArgs e) { CreateWorkThread(); } /// <summary> /// 自动签到方法 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void timer1_Tick(object sender, EventArgs e) { txt_DQDate.Text = DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second; if (txt_DQDate.Text== txt_DateQD.Text) { if (!ThisIsActive()) { this.Activate(); //ControlBox = false; } this.WindowState = FormWindowState.Normal; CreateWorkThread(); } } #endregion #region 添加用户逻辑 /// <summary> /// 添加用户方法 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void textBox1_KeyDown(object sender, KeyEventArgs e) { //Enter键 更新项并隐藏编辑框 if (e.KeyCode == Keys.Enter) { if (!textBox1.Text.Contains(":")) { MessageBox.Show("不包含':'符号,请重新输入"); textBox1.Text = ""; return; } if (textBox1.Text.Split(':')[0].Length!=11) { MessageBox.Show("请输入11位手机号"); textBox1.Text = ""; return; } if (textBox1.Text.Split(':')[1].Length != 4) { MessageBox.Show("请输入身份证号后4位"); textBox1.Text = ""; return; } //添加属性 try { XmlElement xmlElement = XmlDoc.CreateElement("item"); //将节点加入到指定的节点下 xmlElement.InnerText = textBox1.Text; XmlDoc.DocumentElement.PrependChild(xmlElement); XmlDoc.Save(StrPath); txt_Users.Items.Add(textBox1.Text); textBox1.Visible = false; } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } //Esc键 直接隐藏编辑框 if (e.KeyCode == Keys.Escape) textBox1.Visible = false; } /// <summary> /// 显示文本框 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txt_Users_MouseDoubleClick(object sender, MouseEventArgs e) { textBox1.Visible = true; textBox1.Focus(); } /// <summary> /// 加载方法签到用户方法 /// </summary> public void BindListBox() { XmlDoc.Load(StrPath); XmlNodeList topM = XmlDoc.DocumentElement.ChildNodes; foreach (XmlNode item in topM) { txt_Users.Items.Add(item.InnerXml); } } #endregion #region 其他方法 /// <summary> /// 关闭窗体时释放资源和线程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Form1_FormClosing(object sender, FormClosingEventArgs e) { //把整个浏览器的资源释放掉 Cef.Shutdown(); //强制停止所有线程 Environment.Exit(0); } /// <summary> /// 执行JS /// </summary> /// <param name="chromiumWebBrowser">ChromiumWebBrowser</param> /// <param name="js"></param> public static void ExecuteJs(ChromiumWebBrowser chromiumWebBrowser, string js) { var frame = chromiumWebBrowser.GetMainFrame(); frame.EvaluateScriptAsync(js); } /// <summary> /// 写日志 /// </summary> /// <param name="str"></param> static void writeLog(string str) { if (!Directory.Exists("Log")) { Directory.CreateDirectory("Log"); } using (StreamWriter sw = new StreamWriter(@"Log\Log.txt", true)) { sw.WriteLine(str); sw.WriteLine("---------------------------------------------------------"); sw.Close(); } } #endregion

这个程序存在一些问题,例如网络问题,线程问题等等 

但作者的水平有限,只能写成这样了,希望多多指点

posted @ 2020-06-24 09:21  Sumi-eCrow  阅读(2399)  评论(0编辑  收藏  举报