1. 程式人生 > >用golang chromedp 操作已經打開的chrome瀏覽器

用golang chromedp 操作已經打開的chrome瀏覽器

cati demon .text command return tps manual executor hot

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 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) }), } }

用golang chromedp 操作已經打開的chrome瀏覽器