2016-08-02 218 views
0

我想通過在NodeJs上運行javascript代碼來獲取網頁的內容。我希望內容與我在瀏覽器中看到的內容完全相同。如何獲取HTTPS網頁的內容?

這是URLhttps://www.realtor.ca/Residential/Single-Family/17219235/2103-1185-THE-HIGH-STREET-Coquitlam-British-Columbia-V3B0A9

我用下面的代碼,但我得到了response405

var fs = require('fs'); 
var link = 'https://www.realtor.ca/Residential/Single-Family/17219235/2103-1185-THE-HIGH-STREET-Coquitlam-British-Columbia-V3B0A9'; 
var request = require('request'); 
request(link, function (error, response, body) { 
    fs.writeFile("realestatedata.html", body, function(err) { 
     if(err) { 
      console.log('error in saving the file'); 
      return console.log(err); 
     } 
     console.log("The file was saved!"); 
    }); 
}) 

保存的文件與我在瀏覽器中看到的內容無關。

+1

看來您發送的請求不被服務器支持。您是否嘗試過請求('https://www.realtor.ca/Residential/Single-Family/17219235/2103-1185-THE-HIGH-STREET-Coquitlam-British-Columbia-V3B0A9').pipe(fs.createWriteStream( 'realestatedata.html'))? 請注意,無論如何,當您只打開html時頁面將不會呈現相同的方式,因爲它還需要許多其他資源(顯示頁面時會完成110個請求)。 –

+0

我嘗試了以'www'和'realtor.ca'開頭的URL,但都沒有成功。如何才能使它工作?我的意思是我如何運行所有110個請求? –

回答

0

我認爲真正的答案會更容易理解,因爲我的評論被截斷。

看起來您發送的請求的方法不受服務器支持(405方法不允許 - 請求線中指定的方法不允許用於由Request-URI標識的資源。響應必須包含允許標題包含所請求資源的有效方法列表)。你有更多關於HTTP響應的信息嗎? 你有沒有嘗試過下面的代碼而不是你的?

request('https://www.realtor.ca/Residential/Single-Family/17219235/2103-1185-THE-HIGH-STREET-Coquitlam-British-Columbia-V3B0A9').pipe(fs.createWriteStream('realestatedata.html')) 

你也可以看看In Node.js/Express, how do I "download" a page and gets its HTML?

請注意,無論如何,當您只打開html時頁面將不會呈現相同的方式,因爲它還需要許多其他資源(顯示頁面時會完成110個請求)。 我認爲以下答案可以幫助您下​​載整個頁面。 https://stackoverflow.com/a/34935427/1630604

+0

據我所知,它不會顯示在瀏覽器中,而我只想擁有HTML內容(能夠抓取它)。我使用了第一個鏈接中建議的內容,但它不起作用。它會從同一個網站提出一個頁面,但它表示您正在查找的頁面不存在。你的建議也是一樣。 –