将 require('chromedriver).path 直接传递给 selenium-webdriver

Passing require('chromedriver).path directly to selenium-webdriver

tl;dr: 有谁知道如何在不设置 PATH 环境变量的情况下在代码中将 chromedriver 的路径传递给 selenium-webdriver?

我正在尝试将 selenium-webdriver 与 chrome 一起使用,但宁愿不实际安装 chromedriver 并操纵路径。我有以下代码:

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
    withCapabilities(webdriver.Capabilities.chrome()).
    build();

没有在路径中设置 chromedriver,这会引发错误:

Error: The ChromeDriver could not be found on the current PATH. Please download the latest 
version of the ChromeDriver from http://chromedriver.storage.googleapis.com/index.html and 
ensure it can be found on your PATH.

我不想设置我的路径,所以我从 npm 安装了 chromedriver 并添加到我的 package.json:

"scripts": {
    "preinstall-chromedriver": "npm install",
    "install-chromedriver": "node node_modules/chromedriver/install.js",
    "pretest_e2e": "npm run install-chromedriver",
    "test_e2e": "node release/test/rune2e.js"
},

现在我已经安装了 chromedriver 并且可以使用 require('chromedriver').path 获取路径,但是我无法将其传递给 selenium-webdriver。有人知道吗?

您需要创建并设置自己的默认 chrome 服务。

var webdriver = require('selenium-webdriver');
var chrome = require('selenium-webdriver/chrome');
var path = require('chromedriver').path;

var service = new chrome.ServiceBuilder(path).build();
chrome.setDefaultService(service);

var driver = new webdriver.Builder()
    .withCapabilities(webdriver.Capabilities.chrome())
    .build();

您也可以这样做:

require('chromedriver');
const webdriver = require('selenium-webdriver');

const driver = new webdriver.Builder()
    .withCapabilities(webdriver.Capabilities.chrome())
    .build();
Option 1:
process.env.PATH = 'path to chrome driver binary folder';
var driver = new Builder().forBrowser('chrome').build();

Option 2:
install chromedriver (npm install chromedriver)
require('chromedriver'); in your code

//chrome driver will automatically look for chromedriver or chromedriver.exe in the path mentioned based on OS
reference: 
https://github.com/SeleniumHQ/selenium/blob/master/javascript/node/selenium-webdriver/chrome.js line 142
https://github.com/SeleniumHQ/selenium/blob/master/javascript/node/selenium-webdriver/io/index.js line 237