最基本的代碼:
package main import ( "context" "log" "time" "github.com/chromedp/chromedp" ) func main() { log.Printf("自動化助手:") dowork() } func dowork() { //增加選項,允許chrome窗口顯示出來 options := []chromedp.ExecAllocatorOption{ chromedp.Flag("headless", false), chromedp.Flag("hide-scrollbars", false), chromedp.Flag("mute-audio", false), chromedp.UserAgent(`Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36`), } options = append(chromedp.DefaultExecAllocatorOptions[:], options...) //創建chrome窗口 allocCtx, cancel := chromedp.NewExecAllocator(context.Background(), options...) defer cancel() ctx, cancel := chromedp.NewContext(allocCtx) defer cancel() //可以使用多個chromedp.Run() if err := chromedp.Run(ctx, chromedp.Navigate(`http://192.168.132.80/login/Login.jsp?logintype=1`), chromedp.WaitVisible(`#loginid`, chromedp.ByID), chromedp.SendKeys(`input[name=loginid]`, "admin"), chromedp.WaitVisible(`#loginid`, chromedp.ByID), chromedp.SendKeys(`input[name=userpassword]`, "1234"), chromedp.Click(`#login`, chromedp.ByID), //在這里加上你需要的后續操作,如Navigate,SendKeys,Click等 chromedp.Sleep(10*time.Second), ); err != nil { panic(err) } }
常用功能:
1、給input設置值(還可以SendKeys)
chromedp.SetValue(`#loginid`, `aa`, chromedp.ByID),
chromedp.SendKeys(`input[name=userpassword]`, "123"),
2、選擇元素,除chromedp.ByID,還可用 chromedp.ByJSPath
chromedp.SetValue(`document.querySelector("#loginid")`, `bb`, chromedp.ByJSPath),
3、設置值:
chromedp.SetValue(`#loginid`, `cc`, chromedp.ByQuery),
4、延時幾秒:
chromedp.Sleep(10*time.Second),
5、輸出OuterHTML(難點在iframe的選擇)
chromedp.OuterHTML(`document.querySelectorAll("iframe")[3]`, &text1, chromedp.ByJSPath),
6、在頁面上執行javascript
chromedp.EvaluateAsDevTools(`alert("test eval");`, &text1),
7、運行自定義函數
chromedp.ActionFunc(func(ctx context.Context) error {
ioutil.WriteFile("1.txt", []byte(text1), 0777)
return nil
}),
8、獲取iframe內容,頁面有個id=#cke的td,其中有個iframe,用:
document.querySelector("#cke_contents_doccontent > iframe").contentWindow
上面的語句是在chrome console中測試出來的,
在console中$和document.getElementById返回值類型不一樣,一個是數組,可以在console中看出來。
用類似以下語句,獲取和設置iframe中的內容:
document.querySelector("#cke_contents_doccontent > iframe").contentWindow.document.querySelector('p').innerText="aaaa"
9、停止網頁加載(不停止的話,有時會長時間加載)
chromedp.Stop(),
10、等元素出現時
chromedp.WaitVisible(`#docsubject`, chromedp.ByID),
11、等元素消失時
chromedp.WaitNotVisible(`#docsubject`, chromedp.ByID),
12、最后寫了如下代碼
chromedp.Run(ctx, //chromedp.Emulate(device.IPhone7), chromedp.Navigate(`http://192.168.132.80/login/Login.jsp?logintype=1`), chromedp.WaitVisible(`#loginid`, chromedp.ByID), chromedp.Sleep(1*time.Second), chromedp.SendKeys(`input[name=loginid]`, "admin"), chromedp.WaitVisible(`#loginid`, chromedp.ByID), chromedp.SendKeys(`input[name=userpassword]`, "1234"), chromedp.Click(`#login`, chromedp.ByID), chromedp.WaitVisible(`#_ButtonCancel_0`, chromedp.ByID), chromedp.Click(`#_ButtonCancel_0`, chromedp.ByID), chromedp.Stop(), chromedp.Navigate(`http://192.168.132.80/docs/docs/DocAddForCK.jsp?mainid=15&subid=49&secid=1143&showsubmit=1&coworkid=&prjid=&isExpDiscussion=&crmid=&hrmid=&topage=`), chromedp.WaitVisible(`#docsubject`, chromedp.ByID), chromedp.Sleep(1*time.Second), chromedp.SendKeys(`input[name=docsubject]`, "aa11"), //禁止alert彈窗。 防止錯誤提醒;參考我上篇文章,其實不需window.alert = function(){return false;};這種暴力方法! chromedp.EvaluateAsDevTools(`window.alert = function(){return false;};var doc =document.querySelector("#cke_contents_doccontent > iframe").contentWindow.document; p = doc.createElement("p"); p.innerText="abc"; doc.body.append(p);`, &buf), chromedp.Sleep(1*time.Second), chromedp.Click("#BUTTONnull", chromedp.ByID), chromedp.Sleep(1*time.Second), chromedp.Click(`document.querySelector("#BUTTONnull")`, chromedp.ByJSPath), chromedp.ActionFunc(func(ctx context.Context) error { ioutil.WriteFile("1.txt", buf, 0777) return nil }), chromedp.Sleep(2*time.Second), //chromedp.CaptureScreenshot(&buf), )