win7 環境,主要是一開始想在代碼中先用exec.Command啓動chrome,但始終不能成功監聽9222端口,折騰了很長時間,git
須要先手工啓動chrome監聽端口(具體寫在代碼註釋中了)而後再運行代碼,在開源代碼基礎上稍做修改,將訪問不了的google換成sohu。github
效果就是經過代碼將瀏覽器導航到了sohu.comchrome
// Command standalone is a chromedp example demonstrating how to use chromedp // with a standalone (ie, a "pre-existing" / manually started) chrome instance. package main import ( "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)\Google\Chrome\Application\chrome.exe" --remote-debugging-port=9222 //或用下一行在cmd中手工啓動chrome,和上一行的命令相似,注意修改chrome實際路徑,注意命令的前半部分有雙引號,後半部分沒有雙引號 //"C:\Program Files (x86)\Google\Chrome\Application\chrome.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+"\n", 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.png", buf, 0644) }), } }