簡體   English   中英

使用Ruby Mechanize下載作為附件的文件

[英]Using Ruby Mechanize to download file served as attachement

我需要能夠從特定網站獲取報告。 下面的方法可以完成我需要做的所有事情,唯一的收獲是報告“ 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。

服務器似乎正在告訴瀏覽器保存文檔。 線索就是“ Content-disposition:filename”。 機械化將不知道該如何處理,並且會嘗試讀取和解析內容,如果內容為CSV,則將無法正常工作。

如果沒有看到您正在使用的HTML頁面,就不可能確切知道他們使用什么機制來觸發下載。 單擊一個元素可能會觸發一個JavaScript事件,而Mechanize無法處理該事件。 或者,它可以將表單發送到服務器,服務器以文件下載作為響應。 無論哪種情況,您都必須弄清楚要發送的內容,原因以及明確定義所需文檔的內容,然后使用該信息來請求文檔。

機械化不是下載附件的正確工具。 使用Mechanize瀏覽表單,然后使用Mechanize的嵌入式Nokogiri提取文檔的URL。

然后使用遏制或Ruby的內置OpenURI之類的方法檢索附件,或參閱“ 使用WWW:機械化將文件下載到磁盤而不先將其全部加載到內存中 ”以獲取更多信息。

檢查返回頁面page.class的類。 如果是File則可以保存它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM