Golang + selenium 设置无头浏览器模式

前段时间写了个自动化脚本来爬点数据,但是有一个页面的cookies是无法通过发送登录请求来获得的,于是只好使用selenium来加载出页面再获取那个页面的cookies,为了不想每次都打开浏览器页面,因此需要设置无头浏览器,网上查了很久资料特此记录一下解决方法。

func GetAdminCookies(URL string) string {
	//1.开启selenium服务
	//设置selium服务的选项,设置为空。根据需要设置。
	ops := []selenium.ServiceOption{}
	service, err := selenium.NewChromeDriverService("F:\\chromedriver.exe", 9515, ops...)
	if err != nil {
		fmt.Printf("Error starting the ChromeDriver server: %v", err)
	}
	//延迟关闭服务
	defer service.Stop()

	//2.调用浏览器
	//设置浏览器兼容性,我们设置浏览器名称为chrome
	caps := selenium.Capabilities{
		"browserName": "chrome",
	}
	//禁止图片加载,加快渲染速度
	imagCaps := map[string]interface{}{
		"profile.managed_default_content_settings.images": 2,
	}
	//设置实验谷歌浏览器驱动的参数
	chromeCaps := chrome.Capabilities{
		Prefs: imagCaps,
		Args: []string{
			"--headless", //设置Chrome无头模式
		},
	}
	//添加浏览器设置参数
	caps.AddChrome(chromeCaps)
	//调用浏览器urlPrefix
	var wd selenium.WebDriver
	wd, err = selenium.NewRemote(caps, "http://127.0.0.1:9515/wd/hub")
	if err != nil {
		panic(err)
	}
	//延迟退出chrome
	defer wd.Quit()
	err = wd.Get(URL)
	//延迟两秒,等待cookies完全加载出来
	time2.Sleep(2 * time2.Second)
	cookies, err := wd.GetCookies()
	if err != nil {
		fmt.Println(err.Error())
	}
	//fmt.Println(cookies)
	Cookies := ""
	for _, item := range cookies {
		fmt.Println(item.Name, item.Value)
		Cookies = Cookies + fmt.Sprintf(`%s=%s;`, item.Name, item.Value)
	}
	return Cookies
}

其中想要设置无头浏览器,最关键的只是几行代码而已:

Golang + selenium 设置无头浏览器模式_第1张图片 

下面是ChromeOptions类可用的和最常用的参数列表:

start-maximized: 最大化模式打开

Chrome incognito: 无痕浏览打开浏览器

headless: 无头模式(后台运行)

disable-extensions: 禁用Chrome浏览器上现有的扩展

disable-popup-blocking: 禁用弹窗

make-default-browser: 设置Chrome为默认浏览器

version: 打印chrome浏览器版本

disable-infobars: 防止Chrome显示“Chrome正在被自动化软件控制”的通知

你可能感兴趣的:(selenium,go)