wpf使用CefSharp.OffScreen模拟网页登录,并获取身份cookie,C#后台执行js

目录

    • 框架信息:
    • MainWindow.xaml
    • MainWindow.xaml.cs
    • 爬取逻辑
    • 模拟登录
    • 拦截请求
    • Cookie获取 CookieVisitorHandle
    • 完整代码参考项目

框架信息:

  • CefSharp.OffScreen.NETCore 109.1.110

  • .NET 7

  • CefSharp.OffScreen.NETCore

  • v114.2.100 第一版使用这个,此版本不支持windows server 2012 R2;

  • v109.1.110 是支持 Windows 7、Windows 8/8.1、Windows Server 2012、Windows Server 2012 R2 最后一个版本

  • 当前使用v109.1.110

在这里插入图片描述

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://12.189.204.29: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;}}
}

完整代码参考项目

包含有拦截请求,获取响应的代码

https://gitee.com/wanghaoli/rmt_article_zhuanfa

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/204004.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

shiro整合redis

shiro整合redis 前言&#xff1a;shiro默认的session是存储在jvm内存中的&#xff0c;这样会导致java服务内存占用更大以及一旦服务器宕机或者版本迭代需要重启服务时&#xff0c;缓存中的数据不能恢复&#xff0c;导致用户需要重新登录认证&#xff0c;体验很差。因此利用第三…

C++ 泛型编程,函数模版和类模版

1.泛型编程 泛型编程&#xff1a;编写与类型无关的通用代码&#xff0c;是代码复用的一种手段。模板是泛型编程的基础 就比如说活字印刷术&#xff0c;就是提供一个模具&#xff0c;然后根据模具来印刷出不同的字。 泛型编程跟着类似&#xff0c;提供一个模版&#xff0c;根据这…

哈希表——闭散列表

该哈希表实现是闭散列实现法。 闭散列表&#xff1a; 闭散列&#xff1a;也叫开放定址法&#xff0c;当发生哈希冲突时&#xff0c;如果哈希表未被装满&#xff0c;说明在哈希表中必然还有空位置&#xff0c;那么可以把key存放到冲突位置中的“下一个” 空位置中去。 那如何寻…

96.STL-遍历算法 transform

目录 transform 语法&#xff1a; 功能描述&#xff1a; 函数原型&#xff1a; 代码示例&#xff1a; transform 是 C 标准模板库&#xff08;STL&#xff09;中的一个算法&#xff0c;用于对一个范围内的元素进行转换并将结果存储到另一个范围。以下是简要解释和一个示例…

【开源】基于JAVA的衣物搭配系统

项目编号&#xff1a; S 016 &#xff0c;文末获取源码。 \color{red}{项目编号&#xff1a;S016&#xff0c;文末获取源码。} 项目编号&#xff1a;S016&#xff0c;文末获取源码。 目录 一、摘要1.1 项目介绍1.2 项目录屏 二、研究内容2.1 衣物档案模块2.2 衣物搭配模块2.3 衣…

成为AI产品经理——TPR、FPR、ROC、AUC

目录 一、PR图、BEP 1.PR图 2.BEP 二、灵敏度、特异度 1.灵敏度 2.特异度 三、真正率、假正率 1.真正率 2.假正率 三、ROC、AUC 1.ROC 2.AUC 四、KS值 一、PR图、BEP 1.PR图 二分类问题模型通常输出的是一个概率值&#xff0c;我们需要设定一个阈值&#xff…

手机爬虫用Fiddler详细教程

如果你正在进行手机爬虫的工作&#xff0c;那么一款强大而又实用的网络调试工具Fiddler将会是你的好帮手。今天&#xff0c;我将和大家分享一份详细的Fiddler教程&#xff0c;教你如何使用它来轻松捕获和分析手机App的网络请求。让我们一起来探索Fiddler的功能和操作&#xff0…

IntelliJ IDEA 16创建Web项目

首先要理解一个概念&#xff1a;在IntelliJ IDEA中“new Project”相当于eclipse中的工作空间&#xff08;Workspace&#xff09;&#xff0c;而“new Module”相当于eclipse中的工程&#xff08;Project&#xff09;。以下均采用Intellij的说法&#xff0c;请自行对照转换理解…

opencv-图像平滑

高斯平滑 高斯平滑即采用高斯卷积核对图像矩阵进行卷积操作。高斯卷积核是一个近似服从高斯分布的矩阵&#xff0c;随着距离中心点的距离增加&#xff0c;其值变小。这样进行平滑处理时&#xff0c;图像矩阵中锚点处像素值权重大&#xff0c;边缘处像素值权重小。 import cv2 …

PTA-6-48 使用面向对象的思想编写程序描述动物

题目&#xff1a; 使用面向对象的思想编写程序描述动物&#xff0c;说明&#xff1a; &#xff08;1) 分析兔子和青蛙的共性&#xff0c;定义抽象的动物类&#xff0c;拥有一些动物共有的属性&#xff1a;名字、颜色、类别&#xff08;哺乳类、非哺乳类&#xff09;&#xff0c…

在Windows WSL (Linux的Windows子系统)上运行的Ubuntu如何更改主机名

在Windows 安装的Ubuntu&#xff0c;如何修改主机名。有列了两种方法&#xff0c;提供给大家参照。 文章目录 方法一&#xff1a;hostname指令修改方法二&#xff1a;修改配置文件修改hostnanmewsl.conf 文件配置选项推荐阅读 方法一&#xff1a;hostname指令修改 hostname指…

第 373 场 LeetCode 周赛题解

A 循环移位后的矩阵相似检查 模拟 class Solution { public:bool areSimilar(vector<vector<int>> &mat, int k) {int m mat.size(), n mat[0].size();k % n;auto g mat;for (int i 0; i < m; i)if (i & 1)rotate(mat[i].begin(), mat[i].begin() …

MySQL学习day03

一、SQL图形化界面工具 常用比较常用的图形化界面有sqlyog、mavicat、datagrip datagrip工具使用相当方便&#xff0c;功能比前面两种都要强大。 DataGrip工具的安装和使用请查看这篇文档&#xff1a;DataGrip 安装教程 DML-介绍 DML全称是Data Manipulation Language(数据…

什么是高级语言、机器语言、汇编语言?什么是编译和解释?

1、高级语言 计算机程序是一种让计算机执行特定任务的方法。程序是由程序员用一种称为编程语言的特殊语言编写的。编程语言有很多种&#xff0c;例如 C、C、Java、Python 等。这些语言被称为高级语言&#xff0c;因为它们更接近人类的自然语言&#xff0c;而不是计算机能够直接…

电脑便签功能在哪里找?电脑桌面便签怎么添加?

很多上班族在使用电脑办公的时候&#xff0c;都需要随手记录工作事项&#xff0c;例如记录共同工作时的想法、会议笔记、常用工作资料、每天待办的工作任务等事项&#xff0c;这时候使用纸质的笔记本来记录工作&#xff0c;不仅不方便随时查看和使用&#xff0c;而且在修改、删…

final关键字-Java

final关键字 一、使用场景1、当不希望类被继承时&#xff0c;可以用final修饰。2、当不希望父类的某个方法被子类覆盖/重写(override)时&#xff0c;可以用final修饰。3、当不希望类的的某个属性的值被修改&#xff0c;可以用final修饰。4、当不希望某个局部变量被修改&#xf…

Kibana部署

服务器 安装软件主机名IP地址系统版本配置KibanaElk10.3.145.14centos7.5.18042核4G软件版本&#xff1a;nginx-1.14.2、kibana-7.13.2-linux-x86_64.tar.gz 1. 安装配置Kibana &#xff08;1&#xff09;安装 [rootelk ~]# tar zxf kibana-7.13.2-linux-x86_64.tar.gz -C…

第十五届蓝桥杯(Web 应用开发)模拟赛 1 期-大学组(详细分析解答)

目录 1.动态的Tab栏 1.1 题目要求 1.2 题目分析 1.3 源代码 2.地球环游 2.1 题目要求 2.2 题目分析 2.3 源代码 3.迷惑的this 3.1 题目要求 3.2 题目分析 3.3 源代码 4.魔法失灵了 4.1 题目要求 4.2 题目分析 4.3 源代码 5.燃烧你的卡路里 5.1 题目要求 5.2…

SpectralGPT: Spectral Foundation Model 论文翻译1

遥感领域的通用大模型 2023.11.13在CVPR发表 原文地址&#xff1a;[2311.07113] SpectralGPT: Spectral Foundation Model (arxiv.org) 摘要 ​ 基础模型最近引起了人们的极大关注&#xff0c;因为它有可能以一种自我监督的方式彻底改变视觉表征学习领域。虽然大多数基础模型…