145,146版本的谷歌浏览器对cookie的安全管理更上了一层楼,导致直接用selenium直接用getcookies获取不到htponly和Secure类型的cookie。

如何解决这个问题?

可以用DevTools 调试接口的方式来获取,具体代码如下:

1、开启端口调试

options.AddArgument($"--remote-debugging-port=9222");
options.AddArgument("--disable-site-isolation-trials");

2、通过websocket提取

 /// <summary>
    /// 通过 Chrome DevTools 协议获取【全量完整Cookie】
    /// </summary>
    static List<CookieInfo> GetAllCookiesByDevTools()
    {
        try
        {
            // 1. 获取 WebSocket 地址
            string json = new System.Net.WebClient().DownloadString($"http://127.0.0.1:{DebugPort}/json/list");
            var pages = JsonConvert.DeserializeObject<List<PageInfo>>(json);
            string wsUrl = pages[0].webSocketDebuggerUrl;

            // 2. 发送指令获取所有Cookie
            using (var ws = new WebSocket(wsUrl))
            {
                ws.Connect();
                ws.Send("{\"id\":1,\"method\":\"Network.getAllCookies\"}");

                string resp = null;
                ws.OnMessage += (sender, e) => resp = e.Data;

                while (resp == null) Thread.Sleep(10);
                ws.Close();

                // 3. 解析Cookie
                var result = JsonConvert.DeserializeObject<CookieResponse>(resp);
                return result.result.cookies;
            }
        }
        catch
        {
            return new List<CookieInfo>();
        }
    }

完整代码如下;

using System;
using System.Collections.Generic;
using System.Threading;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using WebSocketSharp;
using Newtonsoft.Json;

class ChromeFullCookie
{
    // 固定调试端口
    private const int DebugPort = 9222;

    static void Main(string[] args)
    {
        var options = new ChromeOptions();

        // ✅ 核心:开启远程调试端口
        options.AddArgument($"--remote-debugging-port={DebugPort}");
        options.AddArgument("--disable-site-isolation-trials");

        // 反检测
        options.AddArgument("--disable-blink-features=AutomationControlled");
        options.AddExcludedArgument("enable-automation");

        // 启动浏览器
        var driver = new ChromeDriver(options);
        driver.Manage().Timeouts.ImplicitWait = TimeSpan.FromSeconds(3);

        try
        {
            // 1. 打开目标网站并登录
            driver.Url = "https://你的目标网站.com";
            Thread.Sleep(3000);

            Console.WriteLine("请登录...等待10秒");
            Thread.Sleep(10000);

            // 2. ✅ 获取【完整全量Cookie】
            List<CookieInfo> allCookies = GetAllCookiesByDevTools();

            // 3. 拼接成可用的 Cookie 字符串
            string cookieStr = string.Join("; ", allCookies.ConvertAll(c => $"{c.name}={c.value}"));

            Console.WriteLine("\n======================================");
            Console.WriteLine("🎉 完整Cookie获取成功!");
            Console.WriteLine("Cookie总数:" + allCookies.Count);
            Console.WriteLine("最终可用Cookie:\n" + cookieStr);
            Console.WriteLine("======================================");
        }
        catch (Exception ex)
        {
            Console.WriteLine("错误:" + ex.Message);
        }
        finally
        {
            Console.ReadLine();
            driver.Quit();
        }
    }

    /// <summary>
    /// 通过 Chrome DevTools 协议获取【全量完整Cookie】
    /// </summary>
    static List<CookieInfo> GetAllCookiesByDevTools()
    {
        try
        {
            // 1. 获取 WebSocket 地址
            string json = new System.Net.WebClient().DownloadString($"http://127.0.0.1:{DebugPort}/json/list");
            var pages = JsonConvert.DeserializeObject<List<PageInfo>>(json);
            string wsUrl = pages[0].webSocketDebuggerUrl;

            // 2. 发送指令获取所有Cookie
            using (var ws = new WebSocket(wsUrl))
            {
                ws.Connect();
                ws.Send("{\"id\":1,\"method\":\"Network.getAllCookies\"}");

                string resp = null;
                ws.OnMessage += (sender, e) => resp = e.Data;

                while (resp == null) Thread.Sleep(10);
                ws.Close();

                // 3. 解析Cookie
                var result = JsonConvert.DeserializeObject<CookieResponse>(resp);
                return result.result.cookies;
            }
        }
        catch
        {
            return new List<CookieInfo>();
        }
    }

    // 以下是模型类
    class PageInfo { public string webSocketDebuggerUrl { get; set; } }
    class CookieResponse { public CookieResult result { get; set; } }
    class CookieResult { public List<CookieInfo> cookies { get; set; } }
    public class CookieInfo { public string name { get; set; } public string value { get; set; } }
}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐