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

时间:2015-01-01 19:05:35

标签: javascript node.js selenium selenium-chromedriver

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

我正在尝试使用带有chrome的selenium-webdriver,但更愿意不在物理上安装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。有人知道吗?

3 个答案:

答案 0 :(得分:41)

你需要创建&设置您自己的默认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();

答案 1 :(得分:6)

你也可以这样做:

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

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

答案 2 :(得分:0)

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