LoginSignup
0
0

More than 1 year has passed since last update.

【Ruby】SeleniumでPDFをダウンロードする

Last updated at Posted at 2021-08-07

RubyつかってPDFを自動でダウンロードしたい。
自動でやるにはSeleniumというライブラリをつかう。

つかってみて、ExcelやCSV、HTMLから直どりでデータを取得することができた。

しかし、PDFだけはChromeがViewrモードになって、いっこうにダウンロードできない…。

立ち上げるブラウザのoptionの「always_open_pdf_externally」をtrueにして、
Viewerモードでなく、常にダウンロードできるようにしているはずなのに…!

それが解決できたので、記事として残す。

こんな設定でやってた。

@driver = Selenium::WebDriver.for :chrome

prefs = {
  prompt_for_download: false,
  default_directory: File.absolute_path("./dl")
}

plugins_prefs = {
  always_open_pdf_externally: true
}

options = Selenium::WebDriver::Chrome::Options.new
options.add_preference(:download, prefs )
options.add_preference(:plugins, plugins_prefs ) 
@driver = Selenium::WebDriver.for :chrome, options: options

「always_open_pdf_externally」を文字列にして、
optionの書き方を「:」から「=>」に変える。

なお、「prompt_for_download」などのoptionは文字列にしたら、効かなくなった。

これならダウンロードできた。

  @driver = Selenium::WebDriver.for :chrome

    prefs = {
      :prompt_for_download => false,
      :default_directory => File.absolute_path("./dl")
    }

    plugins_prefs = {
    # 文字列
      'always_open_pdf_externally' => true
    }

    options = Selenium::WebDriver::Chrome::Options.new
    options.add_preference(:download, prefs)
    options.add_preference(:plugins, plugins_prefs)
    @driver = Selenium::WebDriver.for :chrome, :options => options

Seleniumのバグのよう。

参考:
https://stackoverflow.com/questions/66247385/watir-wont-download-pdf-only-opens-in-viewer

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0