1

我需要从特定网站获取报告的能力。下面的方法完成了我需要做的所有事情,唯一的问题是报告“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()也没有显示文件 url 已提交给 Mechanize。

4

2 回答 2

0

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

...
page = page.form_with(:name => "get-report").submit
page.class # File?
page.save('path/to/file')
于 2015-01-15T16:33:41.957 回答
0

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

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

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

然后使用Ruby 的内置OpenURI之类的东西来检索附件,或者参阅“使用 WWW:Mechanize 将文件下载到磁盘而不先将其全部加载到内存中”以获取更多信息。

于 2012-09-19T18:54:06.163 回答