无法在无头模式下启动 Chrome

pal*_*m n 2 ruby ubuntu selenium wsl-2

使用 Windows 子系统 WSL2。我正在尝试在 Ubuntu 20.04 中打开浏览器。

按照命令安装 google chrome 和 chrome-driver

https://tecadmin.net/setup-selenium-chromedriver-on-ubuntu/

通过终端启动 chrome 时遇到问题。也无法初始化浏览器。

版本:

  1. Windows 10
  2. 乌班图20.04
  3. 谷歌浏览器 102.0.5005.61
  4. Chrome驱动程序102.0.5005.61
  5. 硒-webdriver (4.1.0)
  6. 瓦提尔 (7.1.0)

当我尝试通过终端打开 google-chrome 时。

$google-chrome
Run Code Online (Sandbox Code Playgroud)

错误:[0530/135205.172753:错误:exception_handler_server.cc(361)] getsockopt:参数无效(22)

$sudo update-alternatives --config x-www-browser


Selection    Path                           Priority   Status
------------------------------------------------------------
 * 0          /usr/bin/google-chrome-stable   200       auto mode
   1          /usr/bin/chromium-browser       40        manual mode
   2          /usr/bin/google-chrome-stable   200       manual mode        
   3          /usr/bin/wslview                30        manual mode
Run Code Online (Sandbox Code Playgroud)

我也尝试在 IRB 中初始化浏览器。

require 'watir'
browser = Watir::Browser.new(:chrome)
Run Code Online (Sandbox Code Playgroud)

错误:Net::ReadTimeout

也尝试重新安装子系统。仍然面临同样的问题。

Not*_*1ds 6

几个可能的问题:

  • 首先,您提到您使用的是 WSL2,但您收到的 Chrome 错误让我相信您可能使用的是 WSL1。google-chrome如果我在 WSL1 上运行,但在 WSL2 上运行,我会看到相同的错误。

    用 仔细检查一下wsl.exe -l -v。您可能需要使用wsl --set-version <distro> 2.

  • 其次,google-chrome像这样运行,即使在 WSL2 上,也需要 X 服务器。Windows 10 中的 WSL 不支持 GUI 应用程序,因此您需要在 Windows 中安装和配置 X 服务器。您会找到有关该主题的其他问题和答案,因此我不会在这里花太多时间,因为您真正的问题是关于无头运行 Chrome。

  • 只要您运行 WSL2,您就应该能够使用 Watir 运行 Chrome headless。看来您缺少的主要内容是没有headless: true按照此文档调用带有 Chrome 选项的 Watir 。

    以下是我使用 Watir 和 Chromedriver 执行的步骤。请注意,第一行是您链接到的方向的固定版本,因为它需要sudo apt-key add而不是sudo curl

    curl -sS -o - https://dl-ssl.google.com/linux/linux_signing_key.pub | sudo apt-key add
    sudo bash -c "echo 'deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main' >> /etc/apt/sources.list.d/google-chrome.list"
    sudo apt update
    sudo apt install -y google-chrome-stable
    google-chrome --version # To check the Chromedriver version to download
    cd ~
    wget https://chromedriver.storage.googleapis.com/102.0.5005.61/chromedriver_linux64.zip
    
    unzip chromedriver_linux64.zip
    mv chromedriver ~/.local/bin # A directory on your path
    
    gem install --user-install watir 
    
    irb
    
    Run Code Online (Sandbox Code Playgroud)

    在IRB中:

    require 'watir'
    browser = Watir::Browser.new :chrome, headless: true
    browser.goto 'https://stackoverflow.com/q/72432711/11810933'
    puts browser.title
    
    Run Code Online (Sandbox Code Playgroud)

    这会在此处返回您的问题的标题。

    也可以使用该包,如本页headless所述。

    添加以下内容:

    sudo apt install xvfb
    gem install --user-install headless
    
    Run Code Online (Sandbox Code Playgroud)

    然后在irb中:

    sudo apt install xvfb
    gem install --user-install headless
    
    Run Code Online (Sandbox Code Playgroud)