我尝试使用无头chrome浏览器下载文件,但该文件似乎未在任何地方下载。我可以看到它实际上是一项安全功能,可以无限制地限制文件下载,但是,在Ruby中是否有解决方法?尝试了以下代码,但没有运气。
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
})
我希望使用无头chrome浏览器下载文件,但不会发生。
答案 0 :(得分:0)
单击下载链接后,如果在文件开始下载之前在单独的选项卡中打开,则您也需要将上述脚本应用于新打开的选项卡,因为您仅将会话ID设置为当前选项卡,而不是新打开的选项卡。因此,在尝试下载文件之前,请尝试将此脚本应用于新打开的选项卡。我确定它会起作用。
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