我需要能够从特定网站获取报告。下面的方法完成了我需要做的所有事情,唯一的问题是报告“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。
最佳答案
服务器似乎在告诉浏览器保存文档。 “内容处置:文件名”是线索。 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”了解更多信息。
关于ruby - 使用 Ruby Mechanize 下载作为附件的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12499934/