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

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/164683.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/164683.shtml
英文地址,請注明出處:http://en.pswp.cn/news/164683.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

API自動化測試:如何構建高效的測試流程

一、引言 在當前的軟件開發環境中&#xff0c;API&#xff08;Application Programming Interface&#xff09;扮演了極為重要的角色&#xff0c;連接著應用的各個部分。對API進行自動化測試能夠提高測試效率&#xff0c;降低錯誤&#xff0c;確保軟件產品的質量。本文將通過實…

SpringMVC(三)

十、攔截器 1、攔截器的配置 SpringMVC中的攔截器用于攔截控制器方法的執行 SpringMVC中的攔截器需要實現HandlerInterceptor SpringMVC的攔截器必須在SpringMVC的配置文件中進行配置&#xff1a; <bean class"com.atguigu.interceptor.FirstInterceptor">…

constexpt

constexpt constexpt是C11引入的新的關鍵字&#xff0c;它用于在編譯時而非運行時計算函數或變量的值。這個特性對于提高程序效率和優化代非常有用。 編譯時常量和運行時常量 編譯時常量&#xff08;Compile-time Constants&#xff09;和運行時常量&#xff08;Runtime Con…

8年經驗之談 —— 如何使用自動化工具編寫測試用例?

以下為作者觀點&#xff0c;僅供參考&#xff1a; 在快速變化的軟件開發領域&#xff0c;保證應用程序的可靠性和質量至關重要。隨著應用程序復雜性和規模的不斷增加&#xff0c;僅手動測試無法滿足行業需求。 這就是測試自動化發揮作用的地方&#xff0c;它使軟件測試人員能…

leetcode做題筆記1410. HTML 實體解析器

「HTML 實體解析器」 是一種特殊的解析器&#xff0c;它將 HTML 代碼作為輸入&#xff0c;并用字符本身替換掉所有這些特殊的字符實體。 HTML 里這些特殊字符和它們對應的字符實體包括&#xff1a; 雙引號&#xff1a;字符實體為 &quot; &#xff0c;對應的字符是 "…

python appium 官網下載

找了半天吐了 https://github.com/appium/appium-desktop/releases/tag/v1.22.3-4

Hibernate批量處理數據

概念&#xff1a; 批量處理數據是指在一個事務場景中處理大量數據。 在應用程序中難以避免進行批量操作&#xff0c;Hibernate提供了以下方式進行批量處理數據&#xff1a; (1)使用HQL進行批量操作 數據庫層面 executeUpdate() (2)使用JDBC API進行批量操作 數據庫層面 …

Vue學習筆記-Object.defineproperty函數

文章目錄 前文提要Object.defineProperty作用Object.defineProperty參數使用例圖getter&#xff0c;也就是get函數setter&#xff0c;也就是set函數 前文提要 本人僅做個人學習記錄&#xff0c;如有錯誤&#xff0c;請多包涵 Object.defineProperty作用 當在js中聲明了一個變…

王道p150 20.將給定的表達式樹轉化為等價的中綴表達式(通過括號反應操作符的計算次序)

本題代碼如下 void btreetoexp(tree t, char deep) {if (t NULL)return;else if (t->lchild NULL && t->rchild NULL)printf("%c", t->data);//輸出操作數&#xff0c;不加括號else {if (deep > 1)printf("(");btreetoexp(t->l…

Rust語言入門教程(二) - 變量與作用域

變量與作用域 變量的聲明與初始化 Rust的基本語法格式如下&#xff1a; fn main(){let bunnies 2; }語句以分號結尾&#xff0c;用花括號包含語句塊。 Rust的語法其實借鑒了很多其他的語言&#xff0c;比如C語言和Python&#xff0c; 所以變量定義的格式看起來也跟很多我們…

shell 腳本的函數和數組

函數 —— 封裝的一個公式&#xff1a;sin、cos、tan —— 函數為腳本的別名 —— 函數就是一個功能模塊&#xff0c;在函數中寫執行的命令即可&#xff1b;使用函數可以避免代碼重復&#xff0c;增加可讀性&#xff0c;簡化腳本&#xff0c;使用函數可以將大的工程分割為若…

Vue中動態class方法

1.方法一&#xff1a;只需要展示一個class樣式&#xff0c;但是動態取值 <div :class"aaa"></div>data:{return () {aaa:colorRed} }.colorRed {color: red; } 2.方法二&#xff1a;表達式判斷是否展示class里面的樣式 <div :class"{colorRed…

函數與數組

一.函數 1、函數的作用 定義較為復雜的但是需要重復使用的內容&#xff0c;以便再次使用&#xff0c;可以直接調用&#xff0c;節約時間&#xff0c;提高效率。 語句塊定義成函數約等于別名&#xff0c;定義函數&#xff0c;再引用函數。 封裝的可重復利用的具有特定功能的…

python+django高校科研項目管理系統2u3mx

高校科研項目管理系統采用擬開發的高校科研項目管理系統通過測試,確保在最大負載的情況下穩定運轉,各個模塊工作正常,具有較高的可用性。系統整體界面簡潔美觀,用戶使用簡單,滿足用戶需要。在因特網發展迅猛的當今社會,高校科研項目管理系統必然會成為在數字信息化建設的一個重…

Linux 查看 CPU 信息相關命令

目錄 lscpu top htop lscpu lscpu 命令是用于顯示有關 CPU 架構的信息&#xff0c;而不是用于實時監視 CPU 負載。它提供有關 CPU 類型、核心數、線程數、架構等的詳細信息。 lscpu top 命令會顯示系統的實時狀態&#xff0c;包括 CPU 使用率、內存使用率等。按下鍵盤上的…

一文詳解Vue生命周期

Vue是一種流行的用于構建用戶界面的漸進式JavaScript框架。Vue框架在開發過程中&#xff0c;特別強調對生命周期的理解和管理。通過使用生命周期鉤子函數&#xff0c;開發者能夠精確地控制Vue實例的創建、掛載、更新以及銷毀過程。本文將對Vue的生命周期進行詳細的介紹&#xf…

YOLOv8訓練自己的目標檢測數據集

YOLOv8訓練自己的目標檢測數據集 目錄標題 源碼下載環境配置安裝包訓練自己的數據集數據集文件格式數據集文件配置超參數文件配置訓練數據集命令行訓練腳本.py文件訓練 進行detect顯示detect的效果 源碼下載 YOLOv8官方的GitHub代碼&#xff0c;同時上面也有基礎環境的配置要…

IntelliJ IDEA 16創建Web項目

首先要理解一個概念&#xff1a;在IntelliJ IDEA中“new Project”相當于eclipse中的工作空間&#xff08;Workspace&#xff09;&#xff0c;而“new Module”相當于eclipse中的工程&#xff08;Project&#xff09;。以下均采用Intellij的說法&#xff0c;請自行對照轉換理解…

Maven倉庫清除remote.repositories、lastUpdated、sha1腳本

Maven倉庫清除remote.repositories、lastUpdated、sha1腳本 1. 腳本功能 清除本地maven倉庫的_remote.repositories、sha1、lastUpdated的文件 2. 腳本內容 set REPOSITORY_PATH%cd% rem 搜索中... for /f "delims" %%i in (dir /b /s "%REPOSITORY_PATH%\*…

Java 關鍵字:synchronized詳解

synchronized詳解 基本使用源碼解析常見面試題好書推薦 基本使用 Java中的synchronized關鍵字用于在多線程環境下確保數據同步。它可以用來修飾方法和代碼塊 當一個線程訪問一個對象的synchronized方法或代碼塊時&#xff0c;其他線程將無法訪問該對象的其他synchronized方法或…