参考资料

安装

go get -u github.com/chromedp/chromedp

Cookies自动登录

package main

import (
	"context"
	"encoding/json"
	"github.com/chromedp/cdproto/network"
	"github.com/chromedp/chromedp"
	"io/ioutil"
	"log"
	"os"
	"time"
)

func main() {
	// 登陆系统并保存Cookies数据到文件
	GetAllCookies()
	// 读取Cookies文件并自动登录(方法一)
	SetCookie()
	// 读取Cookies文件并自动登录(方法二)
	SetCookies()
}

func GetAllCookies() string {
	opts := append(
		chromedp.DefaultExecAllocatorOptions[:],
		chromedp.Flag("headless", false),
	)

	allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
	defer cancel()

	// 创建chrome实例
	ctx, cancel := chromedp.NewContext(
		allocCtx,
		chromedp.WithLogf(log.Printf),
	)
	defer cancel()
	file, err := os.OpenFile("./cookies", os.O_RDWR|os.O_CREATE, os.ModePerm)
	defer file.Close()
	err = chromedp.Run(ctx,
		chromedp.Navigate(`https://luzhenxiong.top/admin/`),
		chromedp.SetValue(`input[name="username"]`, "admin", chromedp.ByQuery),
		chromedp.SetValue(`input[name="password"]`, "password123", chromedp.ByQuery),
		chromedp.Click(`button`, chromedp.ByQuery),
		chromedp.WaitVisible(`main`, chromedp.ByID),
		chromedp.ActionFunc(func(ctx context.Context) error {
			cookies, err := network.GetAllCookies().Do(ctx)
			if err != nil {
				return err
			}

			j, err := json.Marshal(cookies)
			if err != nil {
				return err
			}

			//【write】写入[]byte类型数据
			_, err = file.Write(j)
			if err != nil {
				return err
			}

			return nil
		}),
	)

	if err != nil {
		log.Fatal(err)
	}
	return file.Name()
}

func SetCookie() {
	opts := append(
		chromedp.DefaultExecAllocatorOptions[:],
		chromedp.Flag("headless", false),
	)

	allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
	defer cancel()

	// 创建chrome实例
	ctx, cancel := chromedp.NewContext(
		allocCtx,
		chromedp.WithLogf(log.Printf),
	)
	defer cancel()
	var text string
	err := chromedp.Run(ctx,
		chromedp.Navigate(`https://luzhenxiong.top/admin/`),
		chromedp.ActionFunc(func(ctx context.Context) error {
			file, err := os.Open("./cookies")
			if err != nil {
				return err
			}

			defer file.Close()
			// 读取文件数据
			jsonBlob, _ := ioutil.ReadAll(file)
			var cookies []network.CookieParam
			// Json解码
			err = json.Unmarshal(jsonBlob, &cookies)
			if err != nil {
				return err
			}
			for _, cookie := range cookies {
				err := network.SetCookie(cookie.Name, cookie.Value).
					WithExpires(cookie.Expires).
					WithDomain(cookie.Domain).
					WithHTTPOnly(true).
					Do(ctx)
				if err != nil {
					return err
				}
			}

			return nil
		}),
		chromedp.Reload(),
		chromedp.Title(&text),
	)

	if err != nil {
		log.Fatal(err)
	}
        time.Sleep(2 * time.Second)
	// 创建用于超时退出的上下文管理器
	ctx, cancel = context.WithTimeout(ctx, 60*time.Second)
	defer cancel()
}

func SetCookies() {
	opts := append(
		chromedp.DefaultExecAllocatorOptions[:],
		chromedp.Flag("headless", false),
	)

	allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...)
	defer cancel()

	// 创建chrome实例
	ctx, cancel := chromedp.NewContext(
		allocCtx,
		chromedp.WithLogf(log.Printf),
	)
	defer cancel()
	var text string
	err := chromedp.Run(ctx,
		chromedp.Navigate(`https://luzhenxiong.top/admin/`),
		chromedp.ActionFunc(func(ctx context.Context) error {
			file, err := os.Open("./cookies")
			if err != nil {
				return err
			}

			defer file.Close()
			// 读取文件数据
			jsonBlob, _ := ioutil.ReadAll(file)
			var cookies []*network.CookieParam
			// Json解码
			err = json.Unmarshal(jsonBlob, &cookies)
			if err != nil {
				return err
			}

			err = network.SetCookies(cookies).Do(ctx)
			if err != nil {
				return err
			}

			return nil
		}),
		chromedp.Reload(),
		chromedp.Title(&text),
	)

	if err != nil {
		log.Fatal(err)
	}
        time.Sleep(2 * time.Second)
	// 创建用于超时退出的上下文管理器
	ctx, cancel = context.WithTimeout(ctx, 60*time.Second)
	defer cancel()
}


可能感兴趣的其他内容