chromedp自动启动为headless模式
1 // Command click is a chromedp example demonstrating how to use a selector to 2 // click on an element. 3 package main 4 5 import ( 6 "context" 7 "fmt" 8 "github.com/chromedp/cdproto/page" 9 "github.com/chromedp/chromedp" 10 "github.com/chromedp/chromedp/runner" 11 "log" 12 "os" 13 "time" 14 ) 15 16 func main() { 17 var err error 18 19 // create context 20 ctxt, cancel := context.WithCancel(context.Background()) 21 defer cancel() 22 23 // create chrome instance 24 //c, err := chromedp.New(ctxt, chromedp.WithLog(log.Printf)) 25 //if err != nil { 26 // log.Fatal(err) 27 //} 28 29 c, err := NewHeadless(ctxt, `https://xxx.xx`) 30 if err != nil { 31 log.Fatalf("new headless: %s",err) 32 } 33 34 // run task list 35 err = c.Run(ctxt, click()) 36 if err != nil { 37 log.Fatalf("task err: %s",err) 38 } 39 40 41 // shutdown chrome 42 err = c.Shutdown(ctxt) 43 if err != nil { 44 log.Fatalf("shutdown err: %s",err) 45 } 46 47 // wait for chrome to finish 48 err = c.Wait() 49 if err != nil { 50 log.Fatalf("wait err: %s",err) 51 } 52 } 53 54 func click() chromedp.Tasks { 55 //url := `https://free-ss.site` 56 //sect := "div.main > div > table > tbody >tr:nth-child(2) > td:nth-child(9) > a" 57 sect := `//a[@href="v/443.json"]` 58 wd,_ := os.Getwd() 59 fmt.Println(wd) 60 return chromedp.Tasks{ 61 //chromedp.Navigate(url), 62 chromedp.WaitVisible(sect), 63 page.SetDownloadBehavior(page.SetDownloadBehaviorBehaviorAllow).WithDownloadPath(wd), 64 chromedp.Click(sect, chromedp.NodeVisible), 65 chromedp.Sleep(3 * time.Second), 66 } 67 } 68 69 70 // NewHeadless 创建headless chrome实例 71 func NewHeadless(ctx context.Context, starturl string) (*chromedp.CDP, error) { 72 // runner.Flag设置启动headless chrome时的命令行参数 73 // Windows用户需要设置runner.Flag("disable-gpu", true),具体信息参见文档的FAQ 74 run, err := runner.New(runner.Flag("headless", false),runner.StartURL(starturl)) 75 76 if err != nil { 77 return nil, err 78 } 79 80 // run.Start启动实例 81 err = run.Start(ctx) 82 if err != nil { 83 return nil, err 84 } 85 86 // 默认情况chromedp会输出大量log,因为是示例所以选择屏蔽,dropChromeLogs为自定义函数,形式为func(string, ...interface{}){} 87 // 使用runner初始化chromedp实例 88 // 实例在使用完毕后需要调用c.Shutdown()来释放资源 89 //c, err := chromedp.New(ctx, chromedp.WithRunner(run), chromedp.WithErrorf(dropChromeLogs)) 90 c, err := chromedp.New(ctx, chromedp.WithRunner(run), chromedp.WithLog(log.Printf)) 91 if err != nil { 92 return nil, err 93 } 94 95 return c, nil 96 }