Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use Chromedp to realize QR Code login in go language

2025-03-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article Xiaobian for you to introduce in detail "go language how to use Chromedp to achieve QR code login", the content is detailed, the steps are clear, the details are handled properly, I hope this "go language how to use Chromedp to achieve QR code login" article can help you solve your doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge.

What is 1 Chromedp?

Chromedp is a faster and simpler Golang library for calling browsers that support the Chrome DevTools protocol without additional dependencies (such as Selenium and PhantomJS)

Both Chrome and Golang have a close relationship with Google, and Chrome DevTools is actually the control terminal after the Chrome browser presses F12.

2 Why not use Selenium

For Golang development, it is more convenient to use chromedp because it only requires a Chrome browser and does not need to rely on ChromeDriver, which eliminates the dependency problem and contributes to automated construction and migration of multi-platform architectures.

3 what needs have been solved by the article

How to use chromedp to login with QR code

How to display the QR code on a non-graphical terminal (makiuchi-d/gozxing decoding skip2/ go-qrcode encoding)

How to save Cookies to achieve login-free for a short time

The website will be updated, and the article is not guaranteed to be updated. Please be sure to learn to follow the example.

4. How to use chromedp to login with QR code 4.1 to install chromedp

Download and install the Chrome browser

Create a Golang project and open Go Module (enter go mod init using the terminal in the project directory)

Use terminal input in the project directory:

Go get-u github.com/chromedp/chromedp

(delete-u if you have dependency problems)

4.2 try to open the website

(take Jinshan document https://account.wps.cn/ as an example)

1. Reset the chromedp to open it with a "head" so that we can debug.

Func main () {/ / chromdp relies on the upper limit of context to pass the parameter ctx, _: = chromedp.NewExecAllocator (context.Background (), / / based on the array configured by default, overriding the headless parameter / / can also be modified according to your own needs. This flag is the browser's settings append (chromedp.DefaultExecAllocatorOptions [:], chromedp.Flag ("headless", false),).)}

two。 Create a chromedp context object

Func main () {/ / chromdp relies on the context upper limit to pass the parameter. / / create a new chromedp context object. The timeout is set regardless of the sequence. / / Note that the second returned parameter is cancel (). It's just that I omitted ctx, _ = context.WithTimeout (ctx, 30*time.Second) ctx, _ = chromedp.NewContext (ctx, / / set the log method chromedp.WithLogf (log.Printf),) / / you can usually use defer cancel () to cancel / / but in the Windows environment We want the program to close the browser by the way / / if you don't want the browser to be closed, use the cancel () method to / / defer cancel () / / defer chromedp.Cancel (ctx)}

3. Perform custom tasks

Func main () {/ / chromdp relies on the context upper limit to pass the parameter. / / create a new chromedp context object. The timeout is set regardless of the sequence. / / Note that the second returned parameter is cancel (), except that I omitted. / / execute our custom task-myTasks function in step 4 if err: = chromedp.Run (ctx, myTasks ()) Err! = nil {log.Fatal (err) return}}

4. Now that the initialization process of the program has been completed, the next task is to open the login page.

/ / Custom task func myTasks () chromedp.Tasks {return chromedp.Tasks {/ / 1. Open the login interface of Jinshan document chromedp.Navigate (loginURL),}}

5. After running the program, you can see that Chrome is opened and visited the website we specified.

4.3 get the QR code (click process)

1. You need to click the Wechat login button, first find the selector of the button, right-click the button and click check in the menu, and then you can see the elements of the button

two。 Right-click the element to open the menu and find the copy selector under copy, that is, get the selector.

3. We try to click the Wechat login button and find that we still need to click OK. Repeat the above steps to get the selector of the confirmation button.

4. Perform the above click steps with code

/ / Custom task func myTasks () chromedp.Tasks {return chromedp.Tasks {/ / 1. Open the login interface of Kingsoft document chromedp.Navigate (loginURL), / / 2. Click Wechat login button / / # wechat > span:nth-child (2) chromedp.Click (`# wechat > span:nth-child (2)`), / / 3. Click the confirm button / / # dialog > div.dialog-wrapper > div > div.dialog-footer > div.dialog-footer-ok chromedp.Click (`# dialog > div.dialog-wrapper > div > div.dialog-footer > div.dialog-footer- ok`),}}

5. Run the program to go directly to the QR code display interface

6. In the same way, get the selector of the QR code picture

7. Using code implementation to obtain QR code

There are two points to note: the first is that the QR code has a loading process, and the second is that the QR code is element rendering.

We need to get it by screenshot (you can also use js to get the corresponding href and download it, but to take care of rookie, choose the simplest one)

Func myTasks () chromedp.Tasks {return chromedp.Tasks {/ / 1. Open the login interface of Kingsoft documents. / / 2. Click the Wechat login button. / / 3. Click the confirm button. / / 4. Get the QR code / / # wximport getCode (),}} func getCode () chromedp.ActionFunc {return func (ctx context.Context) (err error) {/ / 1. Byte slice var code [] byte / / 2 for storing pictures. Screenshot / / Note here you need to note that you need to directly use the ID selector to get the element (chromedp.ByID) if err = chromedp.Screenshot (`# wximport`, & code, chromedp.ByID) .Do (ctx); err! = nil {return} / / 3. Save file if err = ioutil.WriteFile ("code.png", code, 0755); err! = nil {return} return}}

8. If you execute the program, you can find that the QR code picture file has been stored in the directory. We can log in by scanning the QR code, which is the same as that scanned on the browser.

5. How to display the QR code on a non-graphical terminal

(it has nothing to do with chromedp and belongs to extra content)

1. In the above steps, we have obtained the QR code, and then we need to display the QR code on the terminal, the first is decoding, here we use the gozxing library

Func printQRCode (code [] byte) (err error) {/ / 1. Because our byte stream is an image, we need to decode the byte stream img, _, err: = image.Decode (bytes.NewReader (code)) if err! = nil {return} / / 2. Then use the gozxing library to decode the picture to get the binary bitmap bmp, err: = gozxing.NewBinaryBitmapFromImage (img) if err! = nil {return} / / 3. Use binary bitmap decoding to obtain the gozxing res, err: = qrcode.NewQRCodeReader () .Decode (bmp, nil) if err! = nil {return} return}

two。 Then re-encode to output the QR code to the terminal, where the go-qrcode library is used

/ / notice that the library of import has the same name import ("github.com/makiuchi-d/gozxing"github.com/makiuchi-d/gozxing/qrcode" goQrcode "github.com/skip2/go-qrcode") func printQRCode (code [] byte) (err error) {/ / 1. Because our byte stream is an image, we need to decode the byte stream first. / / 2. Then use the gozxing library to decode the picture to get the binary bitmap. / / 3. Use binary bitmap decoding to get the QR code object of gozxing. / / 4. Use the result to get the go-qrcode object (note that I use the alias of the library here) qr, err: = goQrcode.New (res.String (), goQrcode.High) if err! = nil {return} / / 5. Output to standard output stream fmt.Println (qr.ToSmallString (false)) return}

3. Modify the process of our second step

Func getCode () chromedp.ActionFunc {return func (ctx context.Context) (err error) {/ / 1. The byte slice used to store the picture. / / 2. Screenshot / / Note that it needs to be noted here that you directly use the ID selector to get the element (chromedp.ByID). / / 3. Output the QR code to standard output stream if err = printQRCode (code); err! = nil {return err} return}}

3. Run the program to see the effect.

6. How to save Cookies to achieve login-free for a short time

1. In the above process, we can log in by scanning the QR code, and the website will jump after the login. After the jump, we need to save cookies to maintain our login status. The code is as follows

/ / Save Cookiesfunc saveCookies () chromedp.ActionFunc {return func (ctx context.Context) (err error) {/ / wait for the QR code to log in if err = chromedp.WaitVisible (`# app`, chromedp.ByID) .Do (ctx) The err! = nil {return} / / cookies is obtained in the network panel of devTools / / 1. Get cookies cookies, err: = network.GetAllCookies () .Do (ctx) if err! = nil {return} / / 2. Serialize cookiesData, err: = network.GetAllCookiesReturns {Cookies: cookies} .MarshalJSON () if err! = nil {return} / / 3. Store to temporary file if err = ioutil.WriteFile ("cookies.tmp", cookiesData, 0755); err! = nil {return} return}}

two。 After getting the Cookies, we need to load the Cookies from the temporary file into the browser while the program is running

/ / load Cookiesfunc loadCookies () chromedp.ActionFunc {return func (ctx context.Context) (err error) {/ / skip if _, _ err: = os.Stat ("cookies.tmp") if the temporary cookies file does not exist Os.IsNotExist (_ err) {return} / / read the data cookiesData of cookies if present Err: = ioutil.ReadFile ("cookies.tmp") if err! = nil {return} / / deserialize cookiesParams: = network.SetCookiesParams {} if err = cookiesParams.UnmarshalJSON (cookiesData) Err! = nil {return} / / set cookies return network.SetCookies (cookiesParams.Cookies) .Do (ctx)}}

3. Through the above two steps, we have been able to maintain the login status, and then we need to check whether it is successful. Here, call the browser to execute the js script to get the URL of the current page to determine whether it is already a personal central page. If it is true, stop the operation.

/ / check whether to log in to func checkLoginStatus () chromedp.ActionFunc {return func (ctx context.Context) (err error) {var url string if err = chromedp.Evaluate (`_ window.location.href`, & url) .Do (ctx) Err! = nil {return} if strings.Contains (url, "https://account.wps.cn/usercenter/apps") {log.Println (" already logged in using cookies ") chromedp.Stop ()} return}}

4. Finally, just reset our browser task.

/ / Custom task func myTasks () chromedp.Tasks {return chromedp.Tasks {/ / 0. Load cookies div.dialog-wrapper > div > div.dialog-footer > div.dialog-footer-ok. / / 4. Get the QR code / / # wximport. / / 5. If the QR code is logged in, the browser will automatically jump to the user information page

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report