Esaki Raja
Esaki Raja

Reputation: 109

Is there a way to download files using headless chromedriver in Centos using Ruby?

I try to download a file using headless chrome and the file doesn't seems to be getting downloaded anywhere. I could see that it's actually a security feature to restrict file download in headless but, is there a workaround for the same in Ruby? Tried the below code but no luck.

download_path = "#{Pathname.pwd}/test-data/downloaded"
options = Selenium::WebDriver::Chrome::Options.new
options.add_argument("--disable-dev-shm-usage");
options.add_argument('--headless') #Declaring the browser to run in headless mode
options.add_preference(
  :download, directory_upgrade: true,
  prompt_for_download: false,
  default_directory: download_path
)
options.add_preference(:browser, set_download_behavior: { behavior: 'allow' })
@driver = Selenium::WebDriver.for :chrome, options: options #Browser object initialization
set_screen_resolution(1400, 900)
$driver = @driver

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
                        })

I expect the file to be downloaded using headless chrome but it's not happening.

Upvotes: 2

Views: 507

Answers (1)

esakiraja
esakiraja

Reputation: 100

When you click on a download link and if it opens in a separate tab before the file starts downloading, then you need to apply your above mentioned script to the newly opened tab too, because you've set the session id only for the current tab and not for the newly opened tab. So, try apply this script to that newly opened tab before trying to download a file. I'm sure it'll work.

def download_file(label, download_path)
  ele = Locator.new(:xpath, "//ul[@class='cnt']//div[text()='#{label}']/..//a")
  download_url = get_attribute(ele.get_how, ele.get_what, "href")
  @driver.execute_script("window.open()")
  @driver.switch_to.window(@driver.window_handles.last)
  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
    }
  })
  @driver.get(download_url)
  @driver.close
  @driver.switch_to.window(@driver.window_handles.last)
end

Upvotes: 1

Related Questions