使用Ruby Mechanize下载作为附件的文件

时间:2012-09-19 17:33:04

标签: ruby mechanize

我需要能够从特定网站上获取报告。下面的方法执行我需要它做的所有事情,唯一的问题是报告“report.csv”,当页面发布时(页面发布到页面上)在响应标题中提供“content-disposition:filename=report.csv”本身)。

def download_report
  page = @mechanize.click(@mechanize.current_page().link_with(:text => /Reporting/))
  page.form.field_with(:name => "rep").option_with(:value => "adperf").click

  page.form_with(:name => "get-report").field_with(:id => "sasReportingQuery.dateRange").option_with(:value => "Custom").click

  start_date = DateTime.parse(@start_date)
  end_date = DateTime.parse(@end_date)

  page.form_with(:name => "get-report").field_with(:name => "sd_display").value = start_date.strftime("%m/%d/%Y")
  page.form_with(:name => "get-report").field_with(:name => "ed_display").value = end_date.strftime("%m/%d/%Y")
  page.form_with(:name => "get-report").submit
end

据我所知,Mechanize并没有在我可以访问的任何地方捕获文件。有没有办法让Mechanize捕获并下载这个文件?

@mechanize.current_page()不包含该文件,@mechanize.history()未显示文件网址已显示给Mechanize。

2 个答案:

答案 0 :(得分:0)

服务器似乎在告诉浏览器保存文档。 “Content-disposition:filename”是其中的线索。 Mechanize将不知道如何处理,并将尝试读取和解析内容,如果它是CSV,将无法正常工作。

如果没有看到您正在使用的HTML页面,就无法确切地知道他们使用什么机制来触发下载。单击一个元素可以触发一个JavaScript事件,而Mechanize将无法处理该事件。或者,它可以将表单发送到服务器,服务器响应文档下载。在任何一种情况下,您都必须弄清楚发送的内容,原因以及具体定义所需文档的内容,然后使用该信息来请求文档。

Mechanize不是下载附件的正确工具。使用Mechanize导航表单,然后使用Mechanize的嵌入式Nokogiri来提取文档的URL。

然后使用curb或Ruby内置OpenURI之类的内容来检索附件,或参阅“Using WWW:Mechanize to download a file to disk without loading it all in memory first”以获取更多信息。

答案 1 :(得分:0)

检查返回页面page.class的类。如果它是File,那么你可以保存它。

...
page = page.form_with(:name => "get-report").submit
page.class # File?
page.save('path/to/file')
相关问题