用golang chromedp 操作已经打开的chrome浏览器

用golang chromedp 操作已经打开的chrome浏览器

win7 环境,主要是一开始想在代码中先用exec.Command启动chrome,但始终不能成功监听9222端口,折腾了很长时间,

需要先手工启动chrome监听端口,具体写在代码注释中了。

然后再运行代码,代码只是在开源代码基础上稍作修改,将访问不了的google换成sohu。代码效果就是通过代码将浏览器导航到了sohu.com

// Command standalone is a chromedp example demonstrating how to use chromedp// with a standalone (ie, a "pre-existing" / manually started) chrome instance.package mainimport (    "context"    "fmt"    "io/ioutil"    "log"    "time"    "github.com/chromedp/cdproto/cdp"    "github.com/chromedp/chromedp"    "github.com/chromedp/chromedp/client")func main() {    //用cmd中用带 /c start命令,无法成功启动chrome监听端口,    //用exec.Command("C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", "--remote-debugging-port=9222").Run()也不行    //可以在windows cmd 中手工执行下一行的命令启动chrome,注意修改chrome实际路径,另外注意将chrome.exe加入windows防火墙    //cmd /c "C:Program Files (x86)GoogleChromeApplicationchrome.exe"  --remote-debugging-port=9222    //或用下一行在cmd中手工启动chrome,和上一行的命令类似,注意修改chrome实际路径,注意命令的前半部分有双引号,后半部分没有双引号    //"C:Program Files (x86)GoogleChromeApplicationchrome.exe"  --remote-debugging-port=9222    time.Sleep(3 * time.Second)    var err error    // create context    ctxt, cancel := context.WithCancel(context.Background())    defer cancel()    // create chrome    c, err := chromedp.New(ctxt, chromedp.WithTargets(client.New().WatchPageTargets(ctxt)), chromedp.WithLog(log.Printf))    if err != nil {        log.Fatal(err)    }    fmt.Println("ctxt")    // run task list    var site, res string    err = c.Run(ctxt, googleSearch("site:sohu.com", "Easy Money Management", &site, &res))    if err != nil {        log.Fatal(err)    }    log.Printf("saved screenshot of #testimonials from search result listing `%s` (%s)", res, site)}func googleSearch(q, text string, site, res *string) chromedp.Tasks {    var buf []byte    sel := fmt.Sprintf(`//a[text()[contains(., ‘%s‘)]]`, text)    return chromedp.Tasks{        chromedp.Navigate(`https://www.sohu.com`),        chromedp.Sleep(2 * time.Second),        chromedp.WaitVisible(`#hplogo`, chromedp.ByID),        chromedp.SendKeys(`#lst-ib`, q+"", chromedp.ByID),        chromedp.WaitVisible(`#res`, chromedp.ByID),        chromedp.Text(sel, res),        chromedp.Click(sel),        chromedp.Sleep(2 * time.Second),        chromedp.WaitVisible(`#footer`, chromedp.ByQuery),        chromedp.WaitNotVisible(`div.v-middle > div.la-ball-clip-rotate`, chromedp.ByQuery),        chromedp.Location(site),        chromedp.Screenshot(`#testimonials`, &buf, chromedp.ByID),        chromedp.ActionFunc(func(context.Context, cdp.Executor) error {            return ioutil.WriteFile("testimonials.webp", buf, 0644)        }),    }}

推荐阅读