google-chrome - 使用 chromedp 启动具有特定用户配置文件的浏览器

标签 google-chrome selenium testing go browser-automation

我将 selenium 与 python 一起使用,我可以使用它完成所有测试工作 但我正在学习 Golang,我想尝试使用它进行测试 我碰到 chromedp the chromedp github repo 我喜欢它但是 我不知道如何使用特定的用户配置文件启动谷歌浏览器

有人可以帮忙吗?

我正在使用这个例子:

    package main

import (
    "context"
    "fmt"
    "io/ioutil"
    "log"
    "time"

    cdp "github.com/knq/chromedp"
    cdptypes "github.com/knq/chromedp/cdp"
)

func main() {
    var err error

    // create context
    ctxt, cancel := context.WithCancel(context.Background())
    defer cancel()

    // create chrome instance
    c, err := cdp.New(ctxt, cdp.WithLog(log.Printf))
    if err != nil {
        log.Fatal(err)
    }

    // run task list
    var site, res string
    err = c.Run(ctxt, googleSearch("site:brank.as", "Easy Money Management", &site, &res))
    if err != nil {
        log.Fatal(err)
    }

    // shutdown chrome
    err = c.Shutdown(ctxt)
    if err != nil {
        log.Fatal(err)
    }

    // wait for chrome to finish
    err = c.Wait()
    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) cdp.Tasks {
    var buf []byte
    sel := fmt.Sprintf(`//a[text()[contains(., '%s')]]`, text)
    return cdp.Tasks{
        cdp.Navigate(`https://www.google.com`),
        cdp.Sleep(2 * time.Second),
        cdp.WaitVisible(`#hplogo`, cdp.ByID),
        cdp.SendKeys(`#lst-ib`, q+"\n", cdp.ByID),
        cdp.WaitVisible(`#res`, cdp.ByID),
        cdp.Text(sel, res),
        cdp.Click(sel),
        cdp.Sleep(2 * time.Second),
        cdp.WaitVisible(`#footer`, cdp.ByQuery),
        cdp.WaitNotVisible(`div.v-middle > div.la-ball-clip-rotate`, cdp.ByQuery),
        cdp.Location(site),
        cdp.Screenshot(`#testimonials`, &buf, cdp.ByID),
        cdp.ActionFunc(func(context.Context, cdptypes.Handler) error {
            return ioutil.WriteFile("testimonials.png", buf, 0644)
        }),
    }
}

最佳答案

为此你需要使用运行器选项

cdp, err := cdp.New(ctxt, cdp.WithRunnerOptions(
            runner.UserDataDir("<your path>"),
        ))

您可以在下面的链接中查找所有可用选项

https://github.com/knq/chromedp/blob/dc08ecc7272dd745adc3494fb675c76174cbb2b3/runner/runner.go

关于google-chrome - 使用 chromedp 启动具有特定用户配置文件的浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45871304/

相关文章:

java - 用 Selenium 处理日历?

python Selenium 抓取 tbody

java - 在测试中模拟可变网络条件

javascript - A2HS 无法在移动版 chrome 上启动

javascript - 在 chrome 扩展中具有面板行为

google-chrome - Ugly::selection 双色背景

testing - Eclipse RCP 应用程序的自动化 UI 测试

javascript - 透明按钮无法在 Firefox 和 IE 中单击,但在 Chrome 和 Safari 中可以正常工作

c# - 如何使用 Selenium 遍历非选择下拉列表?

testing - cmake 可选测试