chromedp常用语句整理

最基本的代码:

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),
    )
原文地址:https://www.cnblogs.com/pu369/p/12331118.html