DevToolsActivePort file not exist The process started from chrome is no longer running
使用Go进行自动化测试
在Linux上Go使用ChromeDriver进行Webdriver发生一个错误。
panic: unknown error: unknown error: Chrome failed to start: exited abnormally.
(unknown error: DevToolsActivePort file doesn't exist)
(The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
解决方案:(添加粉红字体参数[作用:解决非root无法调用chome问题])
chromeCaps := chrome.Capabilities{
// Prefs: imgCaps,
Path: “”,
Args: []string{
// “–headless”,
“–start-maximized”,
“–window-size=1200x600”,"--no-sandbox",
“–user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36”,
“–disable-gpu”,
“–disable-impl-side-painting”,
“–disable-gpu-sandbox”,
“–disable-accelerated-2d-canvas”,
“–disable-accelerated-jpeg-decoding”,
“–test-type=ui”,
},
}
环境: centos7 go.1.14.4
使用到的工具下载链接:
- wget http://npm.taobao.org/mirrors/chromedriver/83.0.4103.14/chromedriver\_linux64.zip
- chrome浏览器安装自行百度
完整代码(模拟用户登录百度搜索点击)
package main
import (
"fmt"
"time"
"github.com/tebeka/selenium"
"github.com/tebeka/selenium/chrome"
)
const (
//设置常量 分别设置chromedriver.exe的地址和本地调用端口
seleniumPath = `/root/chromedriver`
port = 9515
)
func main() {
chromeCaps := chrome.Capabilities{
// Prefs: imgCaps,
Path: "",
Args: []string{
// "--headless", //不开启浏览器
"--start-maximized",
"--window-size=1200x600",
"--no-sandbox", //非root可运行
"--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
"--disable-gpu",
"--disable-impl-side-painting",
"--disable-gpu-sandbox",
"--disable-accelerated-2d-canvas",
"--disable-accelerated-jpeg-decoding",
"--test-type=ui",
},
}
//1.开启selenium服务
//设置selium服务的选项,设置为空。根据需要设置。
ops := []selenium.ServiceOption{ }
service, err := selenium.NewChromeDriverService(seleniumPath, port, ops...)
if err != nil {
fmt.Printf("Error starting the ChromeDriver server: %v", err)
}
//延迟关闭服务
defer service.Stop()
//2.调用浏览器
//设置浏览器兼容性,我们设置浏览器名称为chrome
caps := selenium.Capabilities{
"browserName": "chrome",
}
caps.AddChrome(chromeCaps)
//调用浏览器urlPrefix: 测试参考:DefaultURLPrefix = "http://127.0.0.1:4444/wd/hub"
wd, err := selenium.NewRemote(caps, "http://127.0.0.1:9515/wd/hub")
if err != nil {
panic(err)
}
//延迟退出chrome
defer wd.Quit()
//3.对页面元素进行操作
//获取百度页面
if err := wd.Get("https://www.baidu.com/"); err != nil {
panic(err)
}
//找到百度输入框id
we, err := wd.FindElement(selenium.ByID, "kw")
if err != nil {
panic(err)
}
//向输入框发送“”
err = we.SendKeys("天下第一")
if err != nil {
panic(err)
}
//找到百度提交按钮id
we, err = wd.FindElement(selenium.ByID, "su")
if err != nil {
panic(err)
}
//点击提交
err = we.Click()
if err != nil {
panic(err)
}
//睡眠20秒后退出
time.Sleep(20 * time.Second)
}
还没有评论,来说两句吧...