ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 概述 ``` // Command download_file is a chromedp example demonstrating how to do headless // file downloads. // // Note that for this technique to work, the file type must trigger the // "Download / Save As" browser dialog. See the download_image example for how // to save a file which would load inside the browser window without triggering // a download. package main import ( "context" "fmt" "log" "os" "path/filepath" "strings" "time" "github.com/chromedp/cdproto/browser" "github.com/chromedp/chromedp" ) func main() { opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.Flag("headless", false), ) allocator, cancelFunc := chromedp.NewExecAllocator(context.Background(), opts...) defer cancelFunc() // create context ctx, cancel := chromedp.NewContext( allocator, chromedp.WithLogf(log.Printf), ) defer cancel() // create a timeout as a safety net to prevent any infinite wait loops ctx, cancel = context.WithTimeout(ctx, 60*time.Second) defer cancel() // set up a channel, so we can block later while we monitor the download // progress done := make(chan string, 1) // set up a listener to watch the download events and close the channel // when complete this could be expanded to handle multiple downloads // through creating a guid map, monitor download urls via // EventDownloadWillBegin, etc chromedp.ListenTarget(ctx, func(v interface{}) { if ev, ok := v.(*browser.EventDownloadProgress); ok { completed := "(unknown)" if ev.TotalBytes != 0 { completed = fmt.Sprintf("%0.2f%%", ev.ReceivedBytes/ev.TotalBytes*100.0) } log.Printf("state: %s, completed: %s\n", ev.State.String(), completed) if ev.State == browser.DownloadProgressStateCompleted { done <- ev.GUID close(done) } } }) // get working directory wd, err := os.Getwd() if err != nil { log.Fatal(err) } if err := chromedp.Run(ctx, // navigate to the page chromedp.Navigate(`https://github.com/chromedp/examples`), chromedp.Click(`//get-repo//details//summary`, chromedp.NodeReady), // 不设置browser 则默认下到默认路径 browser. SetDownloadBehavior(browser.SetDownloadBehaviorBehaviorAllowAndName). WithDownloadPath(wd). WithEventsEnabled(true), //click the "Download Zip" link when visible chromedp.Click(`//get-repo//a[contains(@data-ga-click, "Repository, download zip")]`, chromedp.NodeVisible, chromedp.BySearch), ); err != nil && !strings.Contains(err.Error(), "net::ERR_ABORTED") { // Note: Ignoring the net::ERR_ABORTED page error is essential here // since downloads will cause this error to be emitted, although the // download will still succeed. log.Fatal(err) } // This will block until the chromedp listener closes the channel guid := <-done // We can predict the exact file location and name here because of how we // configured SetDownloadBehavior and WithDownloadPath log.Printf("wrote %s", filepath.Join(wd, guid+".zip")) } ```