youbbs avatar

chromedp: 纯go 驱动Chrome 开发者工具

🕦 by youbbs

chromedp 这个库比较有趣,相对selenium BrowerDriver 来说,该库不依赖Selenium、PhantomJS 等第三方库,通过Chrome 开发者工具接口实现一些操作,如下图功能:

下面是填写表单登录的例子:

Go:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package main

import (
	"context"
	"log"
	"time"

	"github.com/chromedp/chromedp"
)

func main() {
	var err error

	// create context
	ctxt, cancel := context.WithCancel(context.Background())
	defer cancel()

	// create chrome instance
	c, err := chromedp.New(ctxt, chromedp.WithLog(log.Printf))
	if err != nil {
		log.Fatal(err)
	}

	// run task list
	err = c.Run(ctxt, click())
	if err != nil {
		log.Fatal(err)
	}

	// shutdown chrome
	err = c.Shutdown(ctxt)
	if err != nil {
		log.Fatal(err)
	}

	// wait for chrome to finish
	err = c.Wait()
	if err != nil {
		log.Fatal(err)
	}
}

func click() chromedp.Tasks {
	return chromedp.Tasks{
		chromedp.Navigate(`https://www.youbbs.org/login`),
		chromedp.WaitVisible(`div.footer-wrap`),
		chromedp.SetValue(`#name`, "yourname", chromedp.ByID),
		chromedp.SetValue(`#password`, "yourpw", chromedp.ByID),
		chromedp.Click(`#submit`, chromedp.NodeVisible),
		chromedp.Sleep(150 * time.Second),
	}
}

戳这前往 https://github.com/chromedp/chromedp

💘 相关文章

写一条评论

Based on Golang + fastHTTP + sdb | go1.17.1 Processed in 1ms