簡體   English   中英

使用水豚和硒的Chrome無頭下載pdf

[英]Chrome headless download pdf using capybara and selenium

我在我的Ruby on Rails(5.2.1)項目中使用了帶有Selenium(3.14.0)和Capybara(3.8.0)的chrome headless,我有一個測試工作在Non-headless chrome但不在無頭chrome中。 我在谷歌Chrome穩定版69上使用'--headless'標志。

我用以下設置我的無頭鍍鉻,這適用於所有不下載文件的測試。

download_path="#{Rails.root}/tmp/downloads"

Capybara.register_driver(:headless_chrome) do |app|
  caps = Selenium::WebDriver::Remote::Capabilities.chrome(
    chromeOptions: {
      prefs: {
        'download.default_directory' => download_path,
        "download.extensions_to_open" => "applications/pdf",
        'download.directory_upgrade' => true,
        'download.prompt_for_download' => false,
        'plugins.plugins_disabled' => ["Chrome PDF Viewer"]
      },
      binary: "/opt/google/chrome/google-chrome",
      args: %w[headless disable-gpu window-size=1920,1080]
    }
  )
  Capybara::Selenium::Driver.new(
    app,
    browser: :chrome,
    desired_capabilities: caps
  )
end

我已經讀過我應該向selenium chrome驅動程序發送命令以允許下載,但我無法弄清楚如何使用我的設置。 這是我想要的工作,但我的設置; (不是來自我的代碼庫);

@driver = Selenium::WebDriver.for :chrome, options: options

bridge = @driver.send(:bridge)
path = '/session/:session_id/chromium/send_command'
path[':session_id'] = bridge.session_id
bridge.http.call(:post, path, cmd: 'Page.setDownloadBehavior',
                 params: {
                   behavior: 'allow',
                   downloadPath: download_path
                 })

如何在我的設置中訪問selenium網橋,以便我可以發送此http呼叫?

您不需要再手動發送它作為Selenium::WebDriver::Chrome::Server#download_path=添加到selenium。 您可以通過Capybara::Selenium::Driver實例在驅動程序注冊中進行設置

...
Capybara::Selenium::Driver.new(
  app,
  browser: :chrome,
  desired_capabilities: caps
).tap { |d| d.browser.download_path = <your download path> }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM