2017-10-06 23:30:23 +00:00
|
|
|
// examples/simple/main.go
|
2017-01-24 15:09:23 +00:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"log"
|
|
|
|
"time"
|
|
|
|
|
|
|
|
cdp "github.com/knq/chromedp"
|
|
|
|
cdptypes "github.com/knq/chromedp/cdp"
|
|
|
|
)
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
var err error
|
|
|
|
|
|
|
|
// create context
|
|
|
|
ctxt, cancel := context.WithCancel(context.Background())
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
// create chrome instance
|
2017-02-14 08:41:23 +00:00
|
|
|
c, err := cdp.New(ctxt, cdp.WithLog(log.Printf))
|
2017-01-24 15:09:23 +00:00
|
|
|
if err != nil {
|
|
|
|
log.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
// run task list
|
|
|
|
var site, res string
|
2017-10-06 23:30:23 +00:00
|
|
|
err = c.Run(ctxt, googleSearch("site:brank.as", "Home", &site, &res))
|
2017-01-24 15:09:23 +00:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2017-10-06 23:30:23 +00:00
|
|
|
log.Printf("saved screenshot from search result listing `%s` (%s)", res, site)
|
2017-01-24 15:09:23 +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.WaitVisible(`#hplogo`, cdp.ByID),
|
2017-01-29 03:37:56 +00:00
|
|
|
cdp.SendKeys(`#lst-ib`, q+"\n", cdp.ByID),
|
|
|
|
cdp.WaitVisible(`#res`, cdp.ByID),
|
2017-01-24 15:09:23 +00:00
|
|
|
cdp.Text(sel, res),
|
|
|
|
cdp.Click(sel),
|
2017-10-06 23:30:23 +00:00
|
|
|
cdp.WaitVisible(`a[href="/brankas-for-business"]`, cdp.ByQuery),
|
|
|
|
cdp.WaitNotVisible(`.preloader-content`, cdp.ByQuery),
|
2017-01-24 15:09:23 +00:00
|
|
|
cdp.Location(site),
|
2017-10-06 23:30:23 +00:00
|
|
|
cdp.ScrollIntoView(`.banner-section.third-section`, cdp.ByQuery),
|
|
|
|
cdp.Sleep(2 * time.Second), // wait for animation to finish
|
|
|
|
cdp.Screenshot(`.banner-section.third-section`, &buf, cdp.ByQuery),
|
2017-02-12 04:59:33 +00:00
|
|
|
cdp.ActionFunc(func(context.Context, cdptypes.Handler) error {
|
2017-10-06 23:30:23 +00:00
|
|
|
return ioutil.WriteFile("screenshot.png", buf, 0644)
|
2017-01-24 15:09:23 +00:00
|
|
|
}),
|
|
|
|
}
|
|
|
|
}
|