想要作一个定时自动发送微博的程序,微博API提供了一个接口statuses/share,可是该接口须要注册微博开发者并审核经过(须要有app或者网站)微博应用审核产品指南。所以经过搜索引擎了解到能够经过程序控制chrome浏览器来实现,在GitHub上找到了chromedp
这个包,可是相关文档比较少。这里把我了解和学习这个包,并实现自动化发送微博的过程记录并分享出来。git
GitHub地址:https://github.com/chromedp/chromedpgithub
go get -u github.com/chromedp/chromedp
关于如何使用官方还有一个项目专门来写了几个例子来帮助你们入门,第一次接触能够先用官方的例子试一下。可是这里要注意官方的例子中使用的好多都是在国内被屏蔽的网站,地址:https://github.com/chromedp/examplesgolang
普通模式会在电脑上弹出浏览器窗口,能够在浏览器中看到代码执行的效果,调用完成以后须要关闭掉浏览器。chrome
chrome headless模式不会弹出浏览器窗口,而且你屡次go run main.go
的时候, go 代码运行中断致使后台chrome headless不能退出,致使第二次本地调试失败, 此时解决方案就是本身手动结束chrome进程。
所以在调试go代码的时候不建议使用chrome headless模式。浏览器
chromedp
包默认状况下使用chrome headless模式,因此须要在禁用该模式才会弹出你本地的chrome浏览器。bash
// Command click is a chromedp example demonstrating how to use a selector to // click on an element. package main import ( "context" "log" "time" "github.com/chromedp/chromedp" ) func main() { // 禁用chrome headless opts := append(chromedp.DefaultExecAllocatorOptions[:], chromedp.Flag("headless", false), ) allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), opts...) defer cancel() // create chrome instance ctx, cancel := chromedp.NewContext( allocCtx, chromedp.WithLogf(log.Printf), ) defer cancel() // create a timeout ctx, cancel = context.WithTimeout(ctx, 15*time.Second) defer cancel() // navigate to a page, wait for an element, click var example string err := chromedp.Run(ctx, chromedp.Navigate(`https://golang.org/pkg/time/`), // wait for footer element is visible (ie, page is loaded) chromedp.WaitVisible(`body > footer`), // find and click "Expand All" link chromedp.Click(`#pkg-examples > div`, chromedp.NodeVisible), // retrieve the value of the textarea chromedp.Value(`#example_After .play .input textarea`, &example), ) if err != nil { log.Fatal(err) } log.Printf("Go's time.After example:\n%s", example) }