如何在Docker中将chromedriver路径传递给nodejs selenium-webdriver

如何在Docker中将chromedriver路径传递给nodejs selenium-webdriver

这是我的docker文件。

FROM node:17.2.0

USER root

WORKDIR /LT

RUN apt-get update
  
RUN apt-get install git --yes

COPY /LT .
COPY /LT/test .
COPY ["/LT/package.json", "."]

# Install Google Chrome
RUN apt-get install wget
RUN wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
RUN apt-get install ./google-chrome*.deb --yes

ENV CHROME_BIN=/usr/bin/google-chrome

RUN npm install
RUN npm ci
RUN npm install nodejs
RUN npm install mocha -g
RUN npm install chromedriver -g --unsafe-perm
RUN npm install selenium-webdriver
RUN npm install webdriver-manager
#RUN webdriver-manager update
CMD ["node", "./test/script1.js"]

以下是我的 nodejs javascript 文件,它使用 chrome 启动应用程序并登录。

require("chromedriver");
const {By,Key,Builder} = require("selenium-webdriver");
const chrome = require('selenium-webdriver/chrome');

 
async function getAuthCode(){ 

        const url = "https://abcd.com";
        
       //To wait for browser to build and launch properly
        let driver = await new Builder()
            .forBrowser("chrome")
            .setChromeOptions(new chrome.Options().headless()) 
            
            //.setChromeOptions(new chrome.Options().addArguments(['--no-sandbox','-headless', '--disable-dev-shm-usage']))           
        
            .build();
        
        await driver.get(url);
        console.log(driver);
        const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
        await wait(1 * 20 * 1000);
        await driver.manage().window().setRect({ width: 1552, height: 840 });
        await driver.findElement(By.id("emailInput")).click();
        await driver.findElement(By.id("emailInput")).sendKeys("[email protected]");
        
        await driver.findElement(By.id("submitbutton")).click();
        
        
        
        await wait(1 * 20 * 1000);
       
        
        await driver.quit();
        
        return 'some data';

}
 
async function testAuthCode()
{
    var cCode = await getAuthCode();
    console.log(cCode);
}
testAuthCode();

当我使用上面给出的相同 docker 文件运行我的 docker compose 文件时,出现以下错误。

WebDriverError: unknown error: Chrome failed to start: exited abnormally.
-nodejs-1  |   (unknown error: DevToolsActivePort file doesn't exist)
-nodejs-1  |   (The process started from chrome location /usr/bin/google-chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)
-nodejs-1  |     at Object.throwDecodedError (/LT/node_modules/selenium-webdriver/lib/error.js:539:15)

我知道原因,它无法在默认路径“/usr/bin/google-chrome”找到 chromedriver。

任何一个

  1. 我必须在给定的默认位置安装 chrome 或者
  2. 提供 chrome 实际安装位​​置的路径。

无论哪种情况,我如何在 JavaScript 或 docker 中执行此操作?

PS:该脚本在我本地的 Windows 环境中运行良好。

相关内容