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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM