wpf使用CefSharp.OffScreen模拟网页登录,并获取身份cookie,C#后台执行js
目录
- 框架信息:
- MainWindow.xaml
- MainWindow.xaml.cs
- 爬取逻辑
- 模拟登录
- 拦截请求
- Cookie获取 CookieVisitorHandle
框架信息:
CefSharp.OffScreen.NETCore 119.1.20
MainWindow.xaml
<Window x:Class="Wpf_CHZC_Img_Identy_ApiDataGet.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:d="http://schemas.microsoft.com/expression/blend/2008"xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"xmlns:local="clr-namespace:Wpf_CHZC_Img_Identy_ApiDataGet"mc:Ignorable="d"Loaded="Window_Loaded"WindowStartupLocation="CenterScreen"Title="XXXX数据爬取(风险作业)" Height="900" Width="1000" ><Window.Resources><Style TargetType="DockPanel" x:Key="DockPanel1"><Setter Property="Margin" Value="0,20,0,0"></Setter><Setter Property="FlowDirection" Value="LeftToRight"></Setter><!--<Setter Property="DockPanel." Value="LeftToRight"></Setter>--></Style><Style TargetType="StackPanel" x:Key="StackPanel1"><Setter Property="Margin" Value="0,15,0,0"></Setter><Setter Property="Orientation" Value="Horizontal"></Setter><!--<Setter Property="DockPanel." Value="LeftToRight"></Setter>--></Style><Style TargetType="Label" x:Key="Label2"><Setter Property="FontSize" Value="18"></Setter></Style><Style TargetType="ComboBox" ><Setter Property="FontSize" Value="18"></Setter></Style></Window.Resources><Grid Margin="20"><StackPanel ><Label Content="设置时间点执行爬取数据,爬取成功发送到甲甲转发系统" FontWeight="Bold" FontSize="24"/><StackPanel Style="{StaticResource StackPanel1}" ><Label Style="{StaticResource Label2}">时间1,时分:</Label><ComboBox Name="comboxHour" Width="100" SelectionChanged="comboxHour_SelectionChanged" /><ComboBox Name="comboxMinute" ItemsSource="{Binding Minute}" Width="100" Margin="5,0,0,0" SelectionChanged="comboxHour_SelectionChanged" /><Button Name="btnGoPaqu" Content="立即爬取接口" Width="140" FontSize="18" Margin="5,0,0,0" Click="Button_Click"></Button></StackPanel><StackPanel Style="{StaticResource StackPanel1}" ><Label Style="{StaticResource Label2}">时间2,时分:</Label><!--<ComboBox Name="comboxHour" ItemsSource="{Binding Hour}" DisplayMemberPath="Name" SelectedValuePath="Value" Width="100" />--><ComboBox Name="comboxHour2" Width="100" SelectionChanged="comboxHour_SelectionChanged" /><ComboBox Name="comboxMinute2" Width="100" Margin="5,0,0,0" SelectionChanged="comboxHour_SelectionChanged" /><!--显示是否在工作--><TextBlock Name="lamp" Width="40" Background="Magenta" Margin="50,0,0,0" DockPanel.Dock="Left" ></TextBlock></StackPanel><StackPanel Style="{StaticResource StackPanel1}" ><Label Style="{StaticResource Label2}">时间3,时分:</Label><ComboBox Name="comboxHour3" Width="100" SelectionChanged="comboxHour_SelectionChanged" /><ComboBox Name="comboxMinute3" Width="100" Margin="5,0,0,0" DockPanel.Dock="Left" SelectionChanged="comboxHour_SelectionChanged" /></StackPanel><StackPanel Style="{StaticResource StackPanel1}" ><Label Style="{StaticResource Label2}">时间4,时分:</Label><ComboBox Name="comboxHour4" Width="100" SelectionChanged="comboxHour_SelectionChanged" /><ComboBox Name="comboxMinute4" Width="100" Margin="5,0,0,0" SelectionChanged="comboxHour_SelectionChanged" /></StackPanel><DockPanel Style="{StaticResource DockPanel1}"><!--<ListView Name="listView" Height="100"/>--><TextBox Name="logMsg" FontSize="14" IsReadOnly="True" Height="300" TextWrapping="WrapWithOverflow" ScrollViewer.CanContentScroll="True" ScrollViewer.VerticalScrollBarVisibility="Auto" /></DockPanel><Border BorderBrush="Blue" BorderThickness="1" Margin="0,10,0,0"><StackPanel ><Label Content="发布成功后,甲甲文章信息:" FontSize="14"></Label><TextBox Name="txtResult" IsReadOnly="True" Height="200" FontSize="14" TextWrapping="Wrap"></TextBox></StackPanel></Border></StackPanel></Grid>
</Window>
MainWindow.xaml.cs
using CefSharp;
using CefSharp.OffScreen;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml.Linq;namespace Wpf_CHZC_Img_Identy_ApiDataGet
{/// <summary>/// Interaction logic for MainWindow.xaml/// </summary>public partial class MainWindow : Window{public MainWindow(){InitializeComponent();#endregiontry{var settings = new CefSettings(){CookieableSchemesExcludeDefaults = false,PersistSessionCookies = true,Locale = "zh-CN",UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"};//Perform dependency check to make sure all relevant resources are in our output directory.Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);}catch (Exception ex){LogHelpter.AddLog("Cef.Initialize初始化异常" + ex.Message, null, "error_Cef.Initialize");}//自动登陆,获取身份//this.Dispatcher.Invoke(new Action(async () =>//{// LoginHandle loginHandle = new LoginHandle();// await loginHandle.Login();//}));EventHandler<string> func = (s, e) =>{ShowMsg(e);};//订阅消息, 显示ApiJsonGetHandle.ShowLog += func;ApiJsonGetHandle.DoLogin += (s, e) =>{this.Dispatcher.Invoke(new Action(async () => {//登录失效,从新登录LoginHandle loginHandle = new LoginHandle();await loginHandle.Login();})); };//订阅登录消息LoginHandle.ShowLog += func;//订阅消息,文章发布成功后,显示访问信息ApiJsonGetHandle.SetArticleInfo += (s, e) =>{this.txtResult.Dispatcher.Invoke(new Action(() =>{string txtMsg = "更新时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +System.Environment.NewLine + e;this.txtResult.Text = txtMsg;}));};}public List<ConfigNameValue> Hour = new List<ConfigNameValue>();public List<string> Minute = new List<string>();private void Window_Loaded(object sender, RoutedEventArgs e){Hour.Add(new ConfigNameValue() { Name = "请选择", Value = "" });for (int i = 0; i < 24; i++){string name = i.ToString();if (i < 10){name = "0" + i;}Hour.Add(new ConfigNameValue() { Name = name, Value = name });}//小时选择var hourList = Hour.Select(g => g.Name).ToList();//分钟选择Minute.Add("请选择");for (int i = 0; i < 60; i++){if (i < 10){Minute.Add("0" + i);}else{Minute.Add(i.ToString());}}//---------------第一个this.comboxHour.ItemsSource = hourList;comboxMinute.ItemsSource = Minute;this.comboxHour.SelectedIndex = 0;comboxMinute.SelectedIndex = 0;//---------------第二个comboxHour2.ItemsSource = hourList;comboxMinute2.ItemsSource = Minute;//设置默认选择this.comboxHour2.SelectedIndex = 0;comboxMinute2.SelectedIndex = 0;//---------------第三个comboxHour3.ItemsSource = hourList;comboxMinute3.ItemsSource = Minute;//设置默认选择this.comboxHour3.SelectedIndex = 0;comboxMinute3.SelectedIndex = 0;comboxHour4.ItemsSource = hourList;comboxMinute4.ItemsSource = Minute;this.comboxHour4.SelectedIndex = 0;comboxMinute4.SelectedIndex = 0;//listView.Items.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));//定时爬取var task = new Task(async () =>{while (true){string time1 = string.Empty;string time2 = string.Empty;string time3 = string.Empty;string time4 = string.Empty;comboxHour.Dispatcher.Invoke(() =>{time1 = comboxHour.SelectedValue + ":" + comboxMinute.SelectedValue + ":00";time2 = comboxHour2.SelectedValue + ":" + comboxMinute2.SelectedValue + ":00";time3 = comboxHour3.SelectedValue + ":" + comboxMinute3.SelectedValue + ":00";time4 = comboxHour4.SelectedValue + ":" + comboxMinute4.SelectedValue + ":00";//ShowMsg("执行时间点:" + time1 + "," + time2 + "," + time3);});string hhmm = DateTime.Now.ToString("HH:mm:ss");if ((!string.IsNullOrWhiteSpace(time1) && hhmm.Equals(time1))|| (!string.IsNullOrWhiteSpace(time2) && hhmm.Equals(time2))|| (!string.IsNullOrWhiteSpace(time3) && hhmm.Equals(time3))|| (!string.IsNullOrWhiteSpace(time4) && hhmm.Equals(time4))){ShowMsg("命中时间点" + hhmm + ",执行爬取数据...");//到时间点,爬取记录,爬取很成功,推送到;await DoGetHttpJsonDataAndPush();}//指示灯,显示是否在工作 lamp.Dispatcher.InvokeAsync(() =>{if (DateTime.Now.Second % 2 == 0){lamp.Background = System.Windows.Media.Brushes.LimeGreen;}else{lamp.Background = System.Windows.Media.Brushes.White;}});Thread.Sleep(1000);}}, creationOptions: TaskCreationOptions.LongRunning);task.Start();}/// <summary>/// 立即爬取数据/// </summary>/// <returns></returns>private async Task DoGetHttpJsonDataAndPush(){try{//到时间点,爬取记录,爬取很成功,推送到;var result = await ApiJsonGetHandle.PushToRongMeiTiAsync();if (result.Code == 200){txtResult.Dispatcher.InvokeAsync(() =>{//读取历史jsonstring json = ArticleLocalJsonReadFileHandle.ReadArticle();string txtMsg = "更新时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") +System.Environment.NewLine + json;txtResult.Text = txtMsg;});var info = result.Data as ArticleRongmeti;ShowMsg("调用转发服务成功,ArticleId=" + info?.publish_article_id);}}catch (Exception ex){var ex1 = ex.InnerException ?? ex;string msg = ex1.Message;ShowMsg("DoGetHttpJsonDataAndPush异常" + msg);LogHelpter.AddLog("DoGetHttpJsonDataAndPush异常" + msg);}}private static StringBuilder stringBuilder = new StringBuilder();/// <summary>/// 显示消息/// </summary>/// <param name="msg"></param>/// 创建时间:2023-11-20 15:11:17,public void ShowMsg(string msg){stringBuilder.AppendLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ">" + msg);logMsg.Dispatcher.InvokeAsync(new Action(() =>{logMsg.Text = stringBuilder.ToString();//logMsg.MoveFocus(new TraversalRequest(FocusNavigationDirection.Down));if (!logMsg.IsFocused){logMsg.ScrollToEnd();}}));//清理历史字符串if (stringBuilder.Length > 10000000){stringBuilder.Remove(0, 200);}}//立即爬取,按钮触发private async void Button_Click(object sender, RoutedEventArgs e){btnGoPaqu.IsEnabled = false;await DoGetHttpJsonDataAndPush();btnGoPaqu.IsEnabled = true;}private void comboxHour_SelectionChanged(object sender, SelectionChangedEventArgs e){if (comboxHour.SelectedValue.Equals("请选择")){e.Handled = true;return;}//ShowMsg("选择了" + comboxHour.SelectedValue);TimeConfig timeConfig = new TimeConfig(){Time1 = comboxHour.SelectedValue + ":" + comboxMinute.SelectedValue,Time2 = comboxHour2.SelectedValue + ":" + comboxMinute2.SelectedValue,Time3 = comboxHour3.SelectedValue + ":" + comboxMinute3.SelectedValue,Time4 = comboxHour4.SelectedValue + ":" + comboxMinute4.SelectedValue,};//保存时间设置TimeConfigHandle.WriteTimeConfig(timeConfig);}}
}
爬取逻辑
using CefSharp.DevTools.Audits;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Controls.Ribbon.Primitives;
using System.Windows.Documents;namespace Wpf_CHZC_Img_Identy_ApiDataGet
{/// <summary>/// api接口获取;XX数据获取/// </summary>/// 创建时间:2023-11-20 09:09:55,public class ApiJsonGetHandle{/// <summary>/// 显示消息/// </summary>public static event EventHandler<string>? ShowLog;/// <summary>/// 设置文章信息,到UI 控件展示/// </summary>public static event EventHandler<string>? SetArticleInfo;/// <summary>/// 执行登录,/// </summary>public static event EventHandler DoLogin;/// <summary>/// 成化总厂,接口数据获取/// </summary>/// 创建时间:2023-11-20 09:09:55,public static async Task<string?> GetApiJsonAsync(string cookieValue, string dateStart, string dateEnd, string deptId){try{HttpClient httpClient = new HttpClient();httpClient.Timeout = TimeSpan.FromSeconds(13);//httpClient.DefaultRequestHeaders.Add("Content-Type", "application/json");httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + cookieValue);ShowLog?.Invoke(1, "开始爬取接口数据");//{"startDate":"2023-11-17","endDate":"2023-11-17","deptId":"XNeOZRJIHLSibwHOpFBkH3aL49ZEEVQq"}//HttpContent httpContent = JsonContent.Create("{\"startDate\":\"" + dateStart + "\",\"endDate\":\"" + dateEnd + "\",\"deptId\":\"" + deptId + "\"}");HttpContent httpContent = new StringContent("{\"startDate\":\"" + dateStart + "\",\"endDate\":\"" + dateEnd + "\",\"deptId\":\"" + deptId + "\"}");httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json") { CharSet = "utf-8" };/*http://11.89.104.129:8099/api/system/workPermitScore/riskPublicityPage?pageSize=10&pageNum=1*/string url = MyConfigReader.GetConfigValue("ay_chzc_fxzy_url");var httpResponseMessage = await httpClient.PostAsync(url, httpContent);if (!httpResponseMessage.IsSuccessStatusCode){return null;}string json = await httpResponseMessage.Content.ReadAsStringAsync();ShowLog?.Invoke(1, "获取到接口数据" + json);//"code":401if (json.IndexOf("\"code\":401") >= 0){//登录失效,从新登录DoLogin?.Invoke(1,new EventArgs());//LoginHandle loginHandle = new LoginHandle();//await loginHandle.Login();//等待cookie写入完成await Task.Delay(8 * 1000);}return json;}catch (Exception ex){ShowLog?.Invoke(1, "获取json数据失败:" + ex.Message);LogHelpter.AddLog("获取json数据失败" + ex.ToString(), null, "ApiJsonGetHandle_error");return null;}}/// <summary>/// 推送数据到甲甲/// </summary>/// <returns></returns>/// 创建时间:2023-11-20 11:14:40,public static async Task<ResultPublish> PushToRongMeiTiAsync(){int count = 1;int countRead = 1;Again:string cookieValue = LoginSuccessCookieHandle.ReadCookieValue();if (string.IsNullOrWhiteSpace(cookieValue)){if (count <= 1){//LoginHandle login = new LoginHandle();//await login.Login();DoLogin?.Invoke(1, new EventArgs());count++;goto Again;}if (countRead < 20){cookieValue = LoginSuccessCookieHandle.ReadCookieValue();Thread.Sleep(2000);countRead++;goto Again;}LogHelpter.AddLog("没有获取到身份cookie值", null, "PushToRongMeiTi_error");return new ResultPublish() { Code = 500, Msg = "没有获取到身份cookie值" };}string dateStart = DateTime.Now.ToString("yyyy-MM-dd");string deptId_chzc = MyConfigReader.GetConfigValue("deptId_chzc");//获取XX 接口数据string? json = await GetApiJsonAsync(cookieValue.Trim(), dateStart, dateStart, deptId_chzc);if (string.IsNullOrEmpty(json)){LogHelpter.AddLog("没有数据", "PushToRongMeiTi");return new ResultPublish() { Code = 500, Msg = "没获取到数据" };}if (json.IndexOf("\"code\":401") >= 0){goto Again;}ShowLog?.Invoke(1, "开始推送到甲甲");ArticleRongmeti info = new ArticleRongmeti();info.Title = "XX风险作业api数据";info.HtmlContent = json;info.ColumnID = MyConfigReader.GetConfigValue("column_id");info.News_type = 1;//info.ArticleId = "chzcayxt_fxzy231120"; //DateTime.Now.Ticks.ToString();info.ArticleId = MyConfigReader.GetConfigValue("chzc_publish_origin_id");info.PublishingStartDate = DateTime.Now;LogHelpter.AddLog("接口数据:" + Newtonsoft.Json.JsonConvert.SerializeObject(info), "PushToRongMeiTi_json");ResultPublish result;//检查文章是否已经发布了?有记录的执行修改接口string jsonLocal = ArticleLocalJsonReadFileHandle.ReadArticle();if (!string.IsNullOrWhiteSpace(jsonLocal) && jsonLocal.Length > 0){//执行修改文章var oldInfo = Newtonsoft.Json.JsonConvert.DeserializeObject<RmtResult>(jsonLocal);info.RongmetiArticleId = oldInfo.Data.Rongmeiti_article_id;info.publish_article_id = oldInfo.Data.Publish_article_id;result = await PublishArticelToRongmeti.UpdateArticle(info);}else{//推送到甲甲//var result = await PublishArticelToRongmeti.PublishArticle(info);result = await PublishArticelToRongmeti.PublishArticle(info);}ShowLog?.Invoke(1, $"甲甲转发系统:{result.Code},Publish_article_id={result.Data},{result.Msg}");if (result.Code == 200){更新数据到本地json//ArticleLocalJsonReadFileHandle.WriteArticleToFile(json);long publish_article_id = 0;if (result.Msg.Contains("修改")){publish_article_id = info.publish_article_id;}else{var resutlArticle = Newtonsoft.Json.JsonConvert.DeserializeObject<RmtArticleInfo>(result.Data.ToString());publish_article_id = resutlArticle.Publish_article_id;}//推送成功,需要获取文章在甲甲的信息,比如URL;Task.Run(async () =>{int index = 1;while (index <= 12){bool right = await GetArticleInfo(publish_article_id);if (right) break;index++;Thread.Sleep(2 * 1000);}});}// LogHelpter.AddLog($"调用转发服务接口:状态={result.Code},{result.Msg}", null, "PushToRongMeiTi");return result;}/// <summary>/// 获取发布后,文章信息,包含可访问的甲甲文章url/// </summary>/// <param name="articleId"></param>public static async Task<bool> GetArticleInfo(long publish_article_Id){HttpClient httpClient = new HttpClient();string rmtZhuanFaSeverUrl = PublishArticelToRongmeti.GetRongmeitiPublishArticleUrl();rmtZhuanFaSeverUrl = rmtZhuanFaSeverUrl.Replace("PublishArticle", "ArticleInfo");string sign = MD5Helpter.MD5Encryptbit32Back16HEX(publish_article_Id + PublishArticelToRongmeti.AppSecret);string url = rmtZhuanFaSeverUrl + $"?id={publish_article_Id}&sign={sign}&appid={PublishArticelToRongmeti.AppId}";var responseMessage = await httpClient.GetAsync(url);if (responseMessage.IsSuccessStatusCode){string json = await responseMessage.Content.ReadAsStringAsync();//成功的文章,记录文章信息jsonArticleLocalJsonReadFileHandle.WriteArticleToFile(json);//通知ui控件,显示jsonSetArticleInfo?.Invoke(12233, json);return true;}return false;}}
}
模拟登录
//using CefSharp.Wpf;
using CefSharp;
using CefSharp.OffScreen;
using HalconDotNet;
using System;
using System.Collections.Generic;
using System.Formats.Asn1;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Reflection.Metadata;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Xml.Linq;namespace Wpf_CHZC_Img_Identy_ApiDataGet
{/// <summary>/// 登录模拟/// </summary>/// 创建时间:2023-11-20 15:34:27 public class LoginHandle{/// <summary>/// 登录消息通知/// </summary>public static event EventHandler<string>? ShowLog;/// <summary>/// 标记是否正在登录?独占登录,同一时间不允许多个登录/// </summary>static bool loginDoing = false;/// <summary>/// 登录/// </summary>public async Task Login(){if (loginDoing){return;}loginDoing = true;try{ShowLog?.Invoke(1, "正在登录...");//登录的网页URL, http://10.45.22.33:8233/#/ string testUrl = "http://10.45.22.33:8233/#/";// Create the offscreen Chromium browser.var browser = new ChromiumWebBrowser(testUrl){RequestHandler = new MyRequestHandler()};//browser.Size = new System.Drawing.Size(1920, 20000);// 加载完成browser.FrameLoadEnd += Browser_FrameLoadEnd;//等待内容完成加载var response = await browser.WaitForInitialLoadAsync();ShowLog?.Invoke(1, "登录页,等待内容完成加载...");}catch (Exception ex){loginDoing = false;string msg = ex.Message;ShowLog?.Invoke(1, "登录异常:" + msg);}}private async void Browser_FrameLoadEnd(object? sender, FrameLoadEndEventArgs e){var browser = sender as ChromiumWebBrowser;int checkImgCount = 1;Again_get_imgCode:string html = await browser.GetSourceAsync();ShowLog?.Invoke(1, "处理验证码图片 ");//获取验证码图片 base64//document.querySelector(".login-code-img").src;var imgTask = await browser.GetBrowser().MainFrame.EvaluateScriptAsync("document.querySelector(\".login-code-img\").src;");if (!imgTask.Success){loginDoing = false;ShowLog?.Invoke(1, "验证码图片获取失败 ");return;}System.Drawing.Image img = null;try{string base64Img = imgTask.Result.ToString();ShowLog?.Invoke(1, "base64Img=" + base64Img);base64Img = base64Img.Replace("data:image/gif;base64,", "");byte[] bytes = Convert.FromBase64String(base64Img);MemoryStream memStream = new MemoryStream(bytes);img = System.Drawing.Bitmap.FromStream(memStream);ShowLog?.Invoke(1, "验证码图片base64解析成功 ");}catch (Exception ex){loginDoing = false;ShowLog?.Invoke(1, "验证码base64读取异常 " + ex.Message);if (checkImgCount > 20){return;}checkImgCount++;ShowLog?.Invoke(1, "再次去读取验证码url ");goto Again_get_imgCode;//return;}//图片保存路径string dir = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "imgCode");if (!System.IO.Directory.Exists(dir)){System.IO.Directory.CreateDirectory(dir);}string fileSavePath = System.IO.Path.Combine(dir, DateTime.UtcNow.Ticks + ".jpg");img.Save(fileSavePath);//识别验证码图片ShowLog?.Invoke(1, "识别验证码图片:" + fileSavePath);Identify_codeImg identity_CodeImg = new Identify_codeImg();string identifyCode = identity_CodeImg.action(fileSavePath);int calcValue = 0;/* 计算结果 */string account = "134064"; /* 登录账号 */string password = "an1zan@123"; /* 登录密码 *///输入账号 var accountJs = await browser.GetBrowser().MainFrame.EvaluateScriptAsync(@$"var account23 = document.querySelector('input');account23.value = '{account}';account23.dispatchEvent(new Event('input'));");//输入密码var passwordJs = await browser.GetBrowser().MainFrame.EvaluateScriptAsync(@$"var password = document.querySelector(""input[type = 'password']"");password.value = '{password}';password.dispatchEvent(new Event('input'));");//输入验证码var vcode78Js = await browser.GetBrowser().MainFrame.EvaluateScriptAsync(@$"var vcode78 = document.querySelector(""input[placeholder='验证码']"");vcode78.value = '{calcValue}';vcode78.dispatchEvent(new Event('input'));");//点击登录var buttonClick = await browser.GetBrowser().MainFrame.EvaluateScriptAsync("document.querySelector(\"button\").dispatchEvent(new Event(\"click\"));");ShowLog?.Invoke(1, "点击登录");try{//等待跳转页面var home = await browser.WaitForNavigationAsync(timeout: TimeSpan.FromSeconds(20));var response5 = await browser.WaitForInitialLoadAsync();//string html2 = await browser.GetSourceAsync();}catch (Exception ex){loginDoing = false;var ex2 = ex.InnerException ?? ex;string msg = ex2.Message;}var cookieManager = Cef.GetGlobalCookieManager();CookieVisitorHandle visitor = new CookieVisitorHandle();visitor.OnCookie = cookie =>{string url = cookie.Domain + cookie.Path;ShowLog?.Invoke(1, "获取到cookie=" + cookie.Name + ":" + cookie.Value);if (cookie.Path == "/" && cookie.Name == "Admin-Token"){if (cookie.Value.Length > 0){loginDoing = false;//保存cookie值LoginSuccessCookieHandle.WriteCookieValueToFile(cookie.Value);ShowLog?.Invoke(1, "登录成功");}}};cookieManager.VisitAllCookies(visitor);}}
}
拦截请求
using CefSharp;
using CefSharp.Handler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace Wpf_CHZC_Img_Identy_ApiDataGet
{/// <summary>/// 拦截请求,/// </summary>/// 创建时间:2023-11-17 14:18:38,xxpublic class MyRequestHandler : RequestHandler{protected override IResourceRequestHandler GetResourceRequestHandler(IWebBrowser chromiumWebBrowser, IBrowser browser, IFrame frame, IRequest request, bool isNavigation, bool isDownload, string requestInitiator, ref bool disableDefaultHandling){//if (request.Url.Contains("user/getInfo"))//{// string[] cookie = request.Headers.GetValues("Cookie");//}LogHelpter.AddLog("GetResourceRequestHandler请求url:" + request.Url, null, "MyRequestHandler");return base.GetResourceRequestHandler(chromiumWebBrowser, browser, frame, request, isNavigation, isDownload, requestInitiator, ref disableDefaultHandling);}}
}
Cookie获取 CookieVisitorHandle
using CefSharp;
using System;namespace Wpf_CHZC_Img_Identy_ApiDataGet
{/// <summary>/// Cookie获取/// </summary>/// 创建时间:2023-11-17 15:39:13。作者:xxxpublic class CookieVisitorHandle : ICookieVisitor{/// <summary>/// 处理Cookie,调用者自定义处理实现/// </summary>public Action<Cookie> OnCookie;public void Dispose(){}public bool Visit(Cookie cookie, int count, int total, ref bool deleteCookie){OnCookie?.Invoke(cookie);return true;}}
}
相关文章:

wpf使用CefSharp.OffScreen模拟网页登录,并获取身份cookie,C#后台执行js
目录 框架信息:MainWindow.xamlMainWindow.xaml.cs爬取逻辑模拟登录拦截请求Cookie获取 CookieVisitorHandle 框架信息: CefSharp.OffScreen.NETCore 119.1.20 MainWindow.xaml <Window x:Class"Wpf_CHZC_Img_Identy_ApiDataGet.MainWindow&qu…...

【代码随想录刷题】Day18 二叉树05
文章目录 1.【513】找树左下角的值1.1题目描述1.2 解题思路1.2.1 迭代法思路1.2.2 递归法思路 1.3 java代码实现1.3.1 迭代法java代码实现1.3.2 递归法java代码实现 2. 【112】路径总和2.1题目描述2.2 解题思路2.3 java代码实现 3.【106】从中序与后序遍历序列构造二叉树3.1题目…...

2023.11.25更新关于mac开发APP(flutter)的笔记与整理(实机开发一)
我自己写的笔记很杂,下面的笔记是我在chatgpt4的帮助下完成的,希望可以帮到正在踩坑mac开发APP(flutter)的小伙伴 目标:通过MAC电脑使用flutter框架开发一款适用于苹果手机的一个APP应用 本博客的阅读顺序是…...

万宾科技可燃气体监测仪的功能有哪些?
随着城市人口的持续增长和智慧城市不断发展,燃气作为一种重要的能源供应方式,已经广泛地应用于居民生活和工业生产的各个领域。然而燃气泄漏和安全事故的风险也随之增加,对城市的安全和社会的稳定构成了潜在的威胁。我国燃气管道安全事故的频…...
Binlog vs. Redo Log:数据库日志的较劲【高级】
🎏:你只管努力,剩下的交给时间 🏠 :小破站 Binlog vs. Redo Log:数据库日志的较劲【高级】 前言第一:事务的生命周期事务的生命周期Binlog和Redo Log记录事务的一致性和持久性Binlog的记录过程R…...

移动机器人路径规划(二)--- 图搜索基础,Dijkstra,A*,JPS
目录 1 图搜索基础 1.1 机器人规划的配置空间 Configuration Space 1.2 图搜索算法的基本概念 1.3 启发式的搜索算法 Heuristic search 2 A* Dijkstra算法 2.1 Dijkstra算法 2.2 A*&&Weighted A*算法 2.3 A* 算法的工程实践中的应用 3 JPS 1 图搜索基础 1.1…...

消息中间件——RabbitMQ(四)命令行与管控台的基本操作!
前言 在前面的文章中我们介绍过RabbitMQ的搭建:RabbitMQ的安装过以及各大主流消息中间件的对比:,本章就主要来介绍下我们之前安装的管控台是如何使用以及如何通过命令行进行操作。 1. 命令行操作 1.1 基础服务的命令操作 rabbitmqctl sto…...

性能压测工具:wrk
一般我们压测的时候,需要了解衡量系统性能的一些参数指标,比如。 1、性能指标简介 1.1 延迟 简单易懂。green:一般指响应时间 95线:P95。平均100%的请求中95%已经响应的时间 99线:P99。平均100%的请求中99%已经响应的时间 平…...
[Matlab有限元分析] 2.杆单元有限元分析
1. 一维杆单元有限元分析程序 一维刚单元的局部坐标系(单元坐标系)与全局坐标系相同。 1.1 线性杆单元 如图所示是一个杆单元,由两个节点i和j,局部坐标系的X轴沿着杆的方向,由i节点指向j节点,每个节点有…...

透过对话聊天聊网络tcp三次握手四次挥手
序 说起来网络,就让我想起的就是一张图。我在网上可以为所欲为,反正你又不能顺着网线来打我。接下来我们来详细说一下网络到底是怎么连接的。 TCP三次打招呼 首先我会用男女生之间的聊天方式,来举一个例子。 从tcp三次握手来说,…...

项目管理套路:看这一篇绝对够用❤️
写论文必不可少的,就是创建代码并进行实验。好的项目管理可以让实验进行得更加顺利。本篇博客以一次项目实践为例,介绍项目管理的方法,以及可能遇到的问题,并提供一些可行的解决方案。 目录 项目管理工具开始第一步版本管理十分关…...
华为-算法---测试开发工程师----摘要牛客网
Java面试题---摘要牛客网-CSDN博客package extendNiuKeWang;import java.util.Scanner;public class GoodHuaWei {public static void main(String[] args) {Scanner sc = new Scanner(System.in);int money = sc.nextInt();System.out.println("n值总金额:"+money)…...

python环境搭建-yolo代码跑通-呕心沥血制作(告别报错no module named torch)
安装软件 安装过的可以查看有没有添加环境变量 好的! 我们发车! 如果你想方便快捷的跑通大型项目,那么必须安装以下两个软件: 1.pycharm2.anaconda对应作用: pycharm:专门用来跑通python项目的软件,相当于一个编辑器,可以debug调试,可以接受远程链接调试!anaconda:专…...

Cisco Packet Tracer配置命令——路由器篇
路由基础 路由器用于互联两个或多个网络,具有两项功能:为要转发的数据包选择最佳路径以及将数据包交换到正确的端口,概括为路由选择和分组转发。 路由选择 路由选择就是路由器根据目的IP地址的网络地址部分,通过路由选择算法确…...
setContentsMargins(QMargins()) 是 QWidget 类的成员函数,用于设置小部件的内容边距(Contents Margins)
setContentsMargins(QMargins()) 是 QWidget 类的成员函数,用于设置小部件的内容边距(Contents Margins)。 在 Qt 中,内容边距指的是小部件内部内容与小部件边界之间的空白区域。通过设置内容边距,可以控制和调整小部…...
Redis key 过期监听实现
1.技术背景,想知道 redis 设置了TTL时间的key 过期,且有后续的业务处理的场景可以使用。 bug点: 使用redis 缓存失效监听会有一定的延迟, 过期事件是在redis服务器删除键的时候生成的,而不是在理论上生存时间到达0值得…...

Gee教程2.上下文Context
先来看看Gin框架的简单例子 func main() {engine : gin.Default()engine.GET("/", func(c *gin.Context) {c.String(http.StatusOK, "hello World!")})//监听并启动服务,默认 http://localhost:8080/engine.Run() }//我们自己写的 func main()…...

【从浅识到熟知Linux】基本指定之cat、more和less
🎈归属专栏:从浅学到熟知Linux 🚗个人主页:Jammingpro 🐟每日一句:写完这篇我要去吃晚饭啦!! 文章前言:本文介绍cat、more和less指令三种查看文件的用法并给出示例和截图…...

2018年7月24日 Go生态洞察:Go Cloud实现便携式云编程
🌷🍁 博主猫头虎(🐅🐾)带您 Go to New World✨🍁 🦄 博客首页——🐅🐾猫头虎的博客🎐 🐳 《面试题大全专栏》 🦕 文章图文…...

storyBook常见踩坑报错 和 解决
用StoryBook官网的代码,但报错,Unexpected token’<’ 在js文件中// Button.stories.js|jsx import { Button } from ‘./Button’; export default { component: Button, }; /* *👇 Render functions are a framework specific featur…...
HTML 语义化
目录 HTML 语义化HTML5 新特性HTML 语义化的好处语义化标签的使用场景最佳实践 HTML 语义化 HTML5 新特性 标准答案: 语义化标签: <header>:页头<nav>:导航<main>:主要内容<article>&#x…...
在HarmonyOS ArkTS ArkUI-X 5.0及以上版本中,手势开发全攻略:
在 HarmonyOS 应用开发中,手势交互是连接用户与设备的核心纽带。ArkTS 框架提供了丰富的手势处理能力,既支持点击、长按、拖拽等基础单一手势的精细控制,也能通过多种绑定策略解决父子组件的手势竞争问题。本文将结合官方开发文档,…...

如何在看板中有效管理突发紧急任务
在看板中有效管理突发紧急任务需要:设立专门的紧急任务通道、重新调整任务优先级、保持适度的WIP(Work-in-Progress)弹性、优化任务处理流程、提高团队应对突发情况的敏捷性。其中,设立专门的紧急任务通道尤为重要,这能…...
oracle与MySQL数据库之间数据同步的技术要点
Oracle与MySQL数据库之间的数据同步是一个涉及多个技术要点的复杂任务。由于Oracle和MySQL的架构差异,它们的数据同步要求既要保持数据的准确性和一致性,又要处理好性能问题。以下是一些主要的技术要点: 数据结构差异 数据类型差异ÿ…...
C++中string流知识详解和示例
一、概览与类体系 C 提供三种基于内存字符串的流,定义在 <sstream> 中: std::istringstream:输入流,从已有字符串中读取并解析。std::ostringstream:输出流,向内部缓冲区写入内容,最终取…...

USB Over IP专用硬件的5个特点
USB over IP技术通过将USB协议数据封装在标准TCP/IP网络数据包中,从根本上改变了USB连接。这允许客户端通过局域网或广域网远程访问和控制物理连接到服务器的USB设备(如专用硬件设备),从而消除了直接物理连接的需要。USB over IP的…...

MySQL 知识小结(一)
一、my.cnf配置详解 我们知道安装MySQL有两种方式来安装咱们的MySQL数据库,分别是二进制安装编译数据库或者使用三方yum来进行安装,第三方yum的安装相对于二进制压缩包的安装更快捷,但是文件存放起来数据比较冗余,用二进制能够更好管理咱们M…...

9-Oracle 23 ai Vector Search 特性 知识准备
很多小伙伴是不是参加了 免费认证课程(限时至2025/5/15) Oracle AI Vector Search 1Z0-184-25考试,都顺利拿到certified了没。 各行各业的AI 大模型的到来,传统的数据库中的SQL还能不能打,结构化和非结构的话数据如何和…...

聚六亚甲基单胍盐酸盐市场深度解析:现状、挑战与机遇
根据 QYResearch 发布的市场报告显示,全球市场规模预计在 2031 年达到 9848 万美元,2025 - 2031 年期间年复合增长率(CAGR)为 3.7%。在竞争格局上,市场集中度较高,2024 年全球前十强厂商占据约 74.0% 的市场…...

Linux入门(十五)安装java安装tomcat安装dotnet安装mysql
安装java yum install java-17-openjdk-devel查找安装地址 update-alternatives --config java设置环境变量 vi /etc/profile #在文档后面追加 JAVA_HOME"通过查找安装地址命令显示的路径" #注意一定要加$PATH不然路径就只剩下新加的路径了,系统很多命…...