2013-07-04 43 views
2

我有一個問題和我的任務的問題。我在GruntJs上寫了一些應用程序。 我必須通過gruntJs下載網頁源代碼。用Javascript和grunt將網頁源文件下載到文件中

例如,我有一個頁面:example.com/index.html

我想給Grunt任務提供URL,像這樣: scr: "example.com/index.html"

然後,我必須在文件中有這個源文件,ex: source.txt

我該怎麼做?

+0

有一個看看http://nodejs.org/api/http.html#http_http_request_options_callback。 –

+0

我嘗試使用此代碼。但沒有任何反應......'grunt.log.writeln(res); http.get(「http://www.google.com/index.html」,函數(res){ grunt.log.writeln(「Got response:」+ res.statusCode); })。on 'error',函數(e){gmail.com/grunt.log.writeln(「出錯:」+ e.message); });' – user2365163

+0

你是否遇到'http.get'錯誤? – user568109

回答

3

對此有幾種方法。

首先是來自node.js API的原始http.get,如註釋中所述。這將爲您提供最初的頁面加載服務。問題出現時,該網站廣泛使用JavaScript來建立更多的HTML後,Ajax請求。

第二種方法是使用實​​際的瀏覽器引擎加載網站並執行任何JavaScript &進一步的HTML構建頁面加載運行。最常見的引擎是PhantomJS,它被包裝在一個名爲grunt-lib-phantomjs的Grunt庫中。

幸運的是,有人提供你問什麼就頂一下,做幾乎完全另一層:從上面的鏈接 https://github.com/cburgdorf/grunt-html-snapshot

的例子配置:

grunt.initConfig({ 
    htmlSnapshot: { 
     all: { 
      options: { 
      //that's the path where the snapshots should be placed 
      //it's empty by default which means they will go into the directory 
      //where your Gruntfile.js is placed 
      snapshotPath: 'snapshots/', 
      //This should be either the base path to your index.html file 
      //or your base URL. Currently the task does not use it's own 
      //webserver. So if your site needs a webserver to be fully 
      //functional configure it here. 
      sitePath: 'http://localhost:8888/my-website/', 
      //you can choose a prefix for your snapshots 
      //by default it's 'snapshot_' 
      fileNamePrefix: 'sp_', 
      //by default the task waits 500ms before fetching the html. 
      //this is to give the page enough time to to assemble itself. 
      //if your page needs more time, tweak here. 
      msWaitForPages: 1000, 
      //if you would rather not keep the script tags in the html snapshots 
      //set `removeScripts` to true. It's false by default 
      removeScripts: true, 
      //he goes the list of all urls that should be fetched 
      urls: [ 
       '', 
       '#!/en-gb/showcase' 
      ] 
      } 
     } 
    } 
});