wpf使用CefSharp.OffScreen模拟网页登录,并获取身份cookie

news2024/9/23 15:22:48

目录

    • 框架信息:
    • 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();
  
            #endregion



            try
            {
                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(() =>
                    {
                        //读取历史json
                        string 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":401
                if (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();

                //成功的文章,记录文章信息json
                ArticleLocalJsonReadFileHandle.WriteArticleToFile(json);

                //通知ui控件,显示json
                SetArticleInfo?.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,xx
    public 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。作者:xxx
    public 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.coloradmin.cn/o/1237372.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

虚函数可不可以重载为内联 —— 在开启最大优化时gcc、clang和msvc的表现

下面是对该问题的一种常见回答&#xff1a; 首先&#xff0c;内联是程序员对编译器的一种建议&#xff0c;因此可以在在重载虚函数时在声明处加上inline关键字来修饰&#xff0c; 但是因为虚函数在运行时通过虚函数表&#xff0c;而内联函数在编译时进行代码嵌入&#xff0c;因…

【Spring】之IoC与对象存取

未来的几周时间&#xff0c;大概率我会更新一下Spring家族的一些简单知识。而什么是Spring家族&#xff0c;好多同学还不是很清楚&#xff0c;我先来简单介绍一下吧&#xff1a; 所谓Spring家族&#xff0c;它其实就是一个框架&#xff0c;是基于Servlet再次进行封装的内容。为…

SpringBoot启动后自动打开浏览器访问项目

更简单的一个方法 Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " url); Springboot项目启动后自动打开浏览器访问(超实用)_浏览器访问springboot项目-CSDN博客 Springboot项目启动后自动打开浏览器访问 1、在Springboot项目中每次启动完项…

DeepWalk: Online Learning of Social Representations(2014 ACM SIGKDD)

DeepWalk: Online Learning of Social Representations----《DeepWalk&#xff1a;用于图节点嵌入的在线机器学习算法》 DeepWalk 是将 word2vector 用到 GNN 上 DeepWalk&#xff1a; 将 Graph 的每个节点编码为一个 D 维向量&#xff08;无监督学习&#xff09;&#xff0c;E…

云HIS系统源码,医院管理系信息统源码,融合B/S版四级电子病历系统

医院管理信息系统是以推进公共卫生、医疗、医保、药品、财务监管信息化建设为着力点&#xff0c;整合资源&#xff0c;加强信息标准化和公共服务信息平台建设&#xff0c;逐步实现统一高效、互联互通的管理系统。 SaaS模式Java版云HIS系统&#xff0c;在公立二甲医院应用三年…

企业该怎么选择IP证书

IP证书是一种数字证书&#xff0c;它由权威的数字证书颁发机构&#xff08;CA&#xff09;颁发&#xff0c;部署在只有公网IP地址的站点上&#xff0c;用于在网络中验证身份和保护信息安全。IP证书可以在各种场景下保护网站的信息安全&#xff0c;比如网站vip登录&#xff0c;线…

赛氪荣幸受邀参与中国联合国采购促进会第五次会员代表大会

11 月21 日 &#xff08;星期二&#xff09; 下午14:00&#xff0c;在北京市朝阳区定福庄东街1号中国传媒大学&#xff0c;赛氪荣幸参与中国联合国采购促进会第五次会员代表大会。 2022年以来&#xff0c;联合国采购杯全国大学生英语大赛已经走上了国际舞台&#xff0c;共有来自…

Windows安装Linux双系统教程

&#x1f4bb;Windows安装Linux双系统教程 &#x1f959;资源准备&#x1f354;启动盘制作&#x1f373;分区&#x1f32d;重启电脑&#x1f371;安装Ubuntu &#x1f959;资源准备 &#x1f4a1;下载ubuntu系统、refus启动盘制作程序&#x1f448; &#x1f4a1;一个U盘 &am…

【数据分享】全国1-5级流域、河流矢量数据与水体分布、五级水系数据、八级水系边界范围矢量数据

全国3级流域及各级河流数据:今天给大家分享的数据主要为五个&#xff0c;分别为3级流域、1级河流数据、3级以上河流数据以及4级和5级的河流数据。其中1级河流和3级以上河流数据中存在线状矢量以及面状的湖泊数据&#xff1b;4级和5级的河流数据仅为线状的河流矢量数据。数据中大…

单链表相关面试题--5.合并有序链表

5.合并有序链表 21. 合并两个有序链表 - 力扣&#xff08;LeetCode&#xff09; /* 解题思路&#xff1a; 此题可以先创建一个空链表&#xff0c;然后依次从两个有序链表中选取最小的进行尾插操作进行合并。 */ typedef struct ListNode Node; struct ListNode* mergeTwoList…

Docker上部署mysql(超简单!!!)

拉取mysql镜像 运行如下命令 docker pull mysql:5.7 拉取成功 查看镜像 运行容器 此处部署最新版本的mysql docker run -d --name mysql -p 3307:3306 -e TZAsia/Shanghai -e MYSQL_ROOT_PASSWORD111 mysql --name mysql&#xff1a;给容器起个名字&#xff08;唯一&#xff…

振南技术干货集:制冷设备大型IoT监测项目研发纪实(3)

注解目录 1.制冷设备的监测迫在眉睫 1.1 冷食的利润贡献 1.2 冷设监测系统的困难 &#xff08;制冷设备对于便利店为何如何重要&#xff1f;了解一下你所不知道的便利店和新零售行业。关 于电力线载波通信的论战。&#xff09; 2、电路设计 2.1 防护电路 2.1.1 强电防护…

大模型创业“风投”正劲,AGI Foundathon 大模型创业松活动精彩看点

这是一场万众瞩目的大模型领域盛会。当来自世界各地的顶尖大模型开发者、创业者、投资人汇聚一堂&#xff0c;他们对大模型应用层的思考碰撞出了哪些火花&#xff1f;应运而生了哪些令人眼前一亮的AI-Native产品&#xff1f; 让我们一起来回顾吧&#xff5e;

南京数字孪生赋能工业制造,加速推进制造业数字化转型

随着南京信息技术的迅猛发展和工业管理的不断演进&#xff0c;传统的工业管理方式已经无法满足企业对高效、智能和可持续发展的需求。针对这一情况&#xff0c;数字孪生技术应运而生&#xff0c;为南京工业管理带来了全新的变革和机遇。以数字孪生为理念&#xff0c;三维可视化…

CPSC发布关于亚马逊含有纽扣电池或硬币电池产品的相关规则标准!UL4200A

2023年9月21日&#xff0c;美国消费品安全委员会&#xff08;CPSC&#xff09;在《联邦公报》上发布了纽扣及硬币电池及相关产品的最终规则&#xff08;DFR&#xff09;16 CFR 1263&#xff0c;以保护6岁以下儿童免受电池摄入危害。DFR将于2023年10月23日生效&#xff0c;除非消…

redis的集群

高可用方案 1、持久化 2、高可用 主从复制 哨兵模式 集群 主从复制: 主从复制是redis实现高可用的基础&#xff0c;哨兵模式和集群都是在主从复制的基础之上实现高可用 主从复制实现数据的多机备份&#xff0c;以及读写分离&#xff08;主服务器负责写&#xff0c;从服务器…

排序算法:归并排序、快速排序、堆排序

归并排序 要将一个数组排序&#xff0c;可以先将它分成两半分别排序&#xff0c;然后再将结果合并&#xff08;归并&#xff09;起来。这里的分成的两半&#xff0c;每部分可以使用其他排序算法&#xff0c;也可以仍然使用归并排序&#xff08;递归&#xff09;。 我看《算法》…

酒店预订订房小程序源码系统+多酒店入驻 功能齐全 附带完整的搭建教程

随着互联网的快速发展&#xff0c;越来越多的人选择通过在线预订平台预订酒店。为了满足这一需求&#xff0c;我们开发了这个酒店预订订房小程序源码系统。该系统基于先进的云计算技术和大数据分析&#xff0c;旨在为用户提供更加便捷、智能的酒店预订服务。 以下是部分代码示…

喜爱拍拍宝宝照片的,一定要制作照片书方便保存

​制作照片书&#xff0c;让美好记忆长久保存。随着数码技术的普及&#xff0c;我们拥有了越来越多的照片&#xff0c;但如何妥善保存这些珍贵的回忆呢&#xff1f;一张张照片随意夹在相册里&#xff0c;时间一长&#xff0c;容易丢失或混乱。而照片书则不同&#xff0c;它把多…

前端如何判空

这样判空就会报错 loadNode(node, resolve)console.log("node")console.log(node)if (node.data ! null) {this.get(ctx /publicity/publicityType/typeTreeData?id node.data.id).then((res) > {resolve(res)})}}, 需要这样写&#xff0c;用typeof来做类型判…