如何通过点击链接从浏览器自动下载excel文件,而无需通过“另存为”和watir中的其他窗口。我试图保持操作系统独立,所以不会对使用win32ole gem感兴趣。
答案 0 :(得分:6)
为此任务我调整了我的个人资料首选项
我的代码如下:
Chrome驱动程序:
profile = Selenium::WebDriver::Chrome::Profile.new
profile['download.default_directory'] = download_directory
profile['download.prompt_for_download'] = false
browser = Watir::Browser.new :chrome, :profile => profile
Chrome驱动程序2:
prefs = {
'download' => {
'default_directory' => download_directory,
'prompt_for_download' => false,
'directory_upgrade' => true,
'extensions_to_open' => '',
},
'profile' => {
'default_content_settings' => {'multiple-automatic-downloads' => 1}, #for chrome version olde ~42
'default_content_setting_values' => {'automatic_downloads' => 1}, #for chrome newer 46
'password_manager_enabled' => false,
'gaia_info_picture_url' => true,
}
}
caps = Selenium::WebDriver::Remote::Capabilities.chrome
caps['chromeOptions'] = {'prefs' => prefs}
browser = Watir::Browser.new :chrome, :desired_capabilities => caps
<强>火狐:强>
profile = Selenium::WebDriver::Firefox::Profile.new
profile['browser.download.lastDir'] = download_directory
profile['browser.download.folderList'] = 2
profile['browser.download.dir'] = download_directory
profile['browser.download.manager.showWhenStarting'] = false
profile['browser.helperApps.alwaysAsk.force'] = false
profile['browser.helperApps.neverAsk.openFile'] = "text/csv,application/pdf"
profile['browser.helperApps.neverAsk.saveToDisk'] = "text/csv,application/pdf"
profile['pdfjs.disabled'] = true
browser = Watir::Browser.new :firefox, :profile => profile
(我只为pdf文件工作的firefox示例)
但是selenium浏览器下载有很多错误
chrome或firefox webdriver中的一些问题(如此http://code.google.com/p/chromedriver/issues/detail?id=130) 不允许为文件下载编写好的测试
我为下载文件编写了以下ruby脚本
require ‘rubygems’
require “net/http”
require “uri”
def download(_url, _download_path = ”)
url = URI.parse _url
http_object = Net::HTTP.new(url.host, url.port)
http_object.use_ssl = true if (url.scheme == ‘https’ || url.port == 443)
http_object.start.request_get(url.path) do |response|
start_time = Time.now
response["Content-Disposition"] =~ /^.+?filename=”(.+?)”$/
file_name = $1
file = open(_download_path + file_name, ‘wb’)
length = response['Content-Length'].to_i
response.read_body do |fragment|
file.write(fragment)
end
file.close
file_size = File.size(_download_path + file_name)/1024.0/1024.0
puts “-“*80
puts “Download time – #{Time.now – start_time}”
puts “Download speed – #{file_size/(Time.now – start_time)} MB/s”
puts “-“*80
end
end
download(‘http://storagemadeeasy.com/files/1cf064a30aba6d1b8fbc0fba8ac8be5b.jpg’)
我希望这段代码对那些需要测试文件下载(不是浏览器文件下载对话框窗口)的人有用
答案 1 :(得分:2)
它似乎对每个浏览器都是唯一的。 Alister Scott wrote this&lt;&lt;试试看。