chromedp/examples/edge-simple/main.go

79 lines
1.8 KiB
Go
Raw Normal View History

2017-01-24 15:09:23 +00:00
// +build windows
package main
import (
"context"
2017-02-08 14:41:07 +00:00
"fmt"
"io/ioutil"
2017-01-24 15:09:23 +00:00
"log"
2017-02-08 14:41:07 +00:00
"time"
2017-01-24 15:09:23 +00:00
2017-02-08 14:41:07 +00:00
cdp "github.com/knq/chromedp"
cdptypes "github.com/knq/chromedp/cdp"
2017-01-24 15:09:23 +00:00
"github.com/knq/chromedp/client"
)
func main() {
var err error
// create context
ctxt, cancel := context.WithCancel(context.Background())
defer cancel()
// create edge instance -- FIXME: not able to launch separate process (yet)
/*cdp, err := chromedp.New(ctxt, chromedp.WithRunnerOptions(
runner.EdgeDiagnosticsAdapter(),
))*/
// create edge instance
watch := client.New().WatchPageTargets(ctxt)
2017-02-08 14:41:07 +00:00
c, err := chromedp.New(ctxt, chromedp.WithTargets(watch))
2017-01-24 15:09:23 +00:00
if err != nil {
log.Fatal(err)
}
// run task list
2017-02-08 14:41:07 +00:00
var site, res string
err = c.Run(ctxt, googleSearch("site:brank.as", "Easy Money Management", &site, &res))
2017-01-24 15:09:23 +00:00
if err != nil {
log.Fatal(err)
}
// shutdown chrome
2017-02-08 14:41:07 +00:00
err = c.Shutdown(ctxt)
2017-01-24 15:09:23 +00:00
if err != nil {
log.Fatal(err)
}
2017-02-08 14:41:07 +00:00
// wait for chrome to finish
err = c.Wait()
2017-01-24 15:09:23 +00:00
if err != nil {
log.Fatal(err)
}
2017-02-08 14:41:07 +00:00
log.Printf("saved screenshot of #testimonials from search result listing `%s` (%s)", res, site)
2017-01-24 15:09:23 +00:00
}
2017-02-08 14:41:07 +00:00
func googleSearch(q, text string, site, res *string) cdp.Tasks {
var buf []byte
sel := fmt.Sprintf(`//a[text()[contains(., '%s')]]`, text)
return cdp.Tasks{
cdp.Navigate(`https://www.google.com`),
cdp.Sleep(2 * time.Second),
cdp.WaitVisible(`#hplogo`, cdp.ByID),
cdp.SendKeys(`#lst-ib`, q+"\n", cdp.ByID),
cdp.WaitVisible(`#res`, cdp.ByID),
cdp.Text(sel, res),
cdp.Click(sel),
cdp.Sleep(2 * time.Second),
cdp.WaitVisible(`#footer`, cdp.ByQuery),
cdp.WaitNotVisible(`div.v-middle > div.la-ball-clip-rotate`, cdp.ByQuery),
cdp.Location(site),
cdp.Screenshot(`#testimonials`, &buf, cdp.ByID),
cdp.ActionFunc(func(context.Context, cdptypes.FrameHandler) error {
return ioutil.WriteFile("testimonials.png", buf, 0644)
}),
2017-01-24 15:09:23 +00:00
}
}