| 1 | + | package spider |
| 2 | + | |
| 3 | + | import ( |
| 4 | + | "context" |
| 5 | + | "fmt" |
| 6 | + | "github.com/chromedp/cdproto/network" |
| 7 | + | "log" |
| 8 | + | "testing" |
| 9 | + | "time" |
| 10 | + | |
| 11 | + | "github.com/chromedp/chromedp" |
| 12 | + | ) |
| 13 | + | |
| 14 | + | // https://github.com/chromedp/examples |
| 15 | + | func Test_Name(t *testing.T) { |
| 16 | + | // create chrome instance |
| 17 | + | ctx, cancel := chromedp.NewContext( |
| 18 | + | context.Background(), |
| 19 | + | chromedp.WithLogf(log.Printf), |
| 20 | + | ) |
| 21 | + | defer cancel() |
| 22 | + | |
| 23 | + | // create a timeout |
| 24 | + | ctx, cancel = context.WithTimeout(ctx, 15*time.Second) |
| 25 | + | defer cancel() |
| 26 | + | |
| 27 | + | // navigate to a page, wait for an element, click |
| 28 | + | var example string |
| 29 | + | err := chromedp.Run(ctx, |
| 30 | + | chromedp.Navigate(`https://www.baidu.com/`), |
| 31 | + | // // wait for footer element is visible (ie, page is loaded) |
| 32 | + | chromedp.WaitVisible(`body`), |
| 33 | + | // // find and click "Expand All" link |
| 34 | + | // chromedp.Click(`#pkg-examples > div`, chromedp.NodeVisible), |
| 35 | + | // // retrieve the value of the textarea |
| 36 | + | // chromedp.Value(`document.cookies`, &example), |
| 37 | + | chromedp.ActionFunc(func(ctx context.Context) error { |
| 38 | + | cookies, err := network.GetAllCookies().Do(ctx) |
| 39 | + | if err != nil { |
| 40 | + | return err |
| 41 | + | } |
| 42 | + | for _, cookie := range cookies { |
| 43 | + | example += fmt.Sprintf("%v", cookie) + ";" |
| 44 | + | } |
| 45 | + | return nil |
| 46 | + | }), |
| 47 | + | ) |
| 48 | + | if err != nil { |
| 49 | + | log.Fatal(err) |
| 50 | + | } |
| 51 | + | fmt.Printf("Go's time.After example:\n%s", example) |
| 52 | + | } |
| 53 | + | |