使用Watir Webdriver下载文件

时间:2015-10-19 21:55:35

标签: ruby google-chrome download watir-webdriver

我想使用Watir Webdriver从页面下载文件。我需要能够将下载位置设置为我定义的目录。我找到this page,但那里的代码不起作用:

profile = Selenium::WebDriver::Chrome::Profile.new
profile['download.prompt_for_download'] = false
profile['download.default_directory'] = download_directory

b = Watir::Browser.new :chrome, :profile => profile

(其中download_directory只是我的桌面)给出了这个:

Selenium::WebDriver::Error::UnknownError: unknown error: cannot parse capability: chromeOptions
from unknown error: unrecognized chrome option: profile
  (Driver info: chromedriver=2.19.346063 (38b35413bd4a486d436a9749e090454bc9ff6708),platform=Mac OS X 10.11.0 x86_64)
from /Users/myusername/.rvm/gems/ruby-1.9.3-p551/gems/selenium-webdriver-2.48.1/lib/selenium/webdriver/remote/response.rb:70:in `assert_ok'

我猜这段代码是旧版本的Watir。如何通过Watir设置Chrome的下载位置?

2 个答案:

答案 0 :(得分:4)

您的示例适用于的旧版Chrome(webdriver 1),您必须使用以下代码:

prefs = {
    'download' => {
        'default_directory' => download_directory,
        'prompt_for_download' => false,
    },
    'profile' => {
        'default_content_settings' => {'multiple-automatic-downloads' => 1}, #for chrome version olde ~42
        'default_content_setting_values' => {'automatic_downloads' => 1}, #for chrome newe 46
    }
}

caps = Selenium::WebDriver::Remote::Capabilities.chrome
caps['chromeOptions'] = {:prefs => prefs}

b = Watir::Browser.new :chrome, :desired_capabilities => caps

你可以在我的旧问题answer中使用这个问题

答案 1 :(得分:3)

Stephan's answer的基础上,我发现我可以使用这个更短/更清洁的版本:

preferences = { 
  :download => {
    :prompt_for_download => false,
    :directory_upgrade => true,
    :default_directory => "download_directory"
  }   
}   

browser = Watir::Browser.new :chrome, :prefs => preferences