簡體   English   中英

在 Node.js / Express 中,我如何“下載”頁面並獲取其 HTML?

[英]In Node.js / Express, how do I “download” a page and gets its HTML?

在代碼中,我想下載“http://www.google.com”並將其存儲在一個字符串中。 我知道如何在 python 的 urllib 中做到這一點。 但是你如何在 Node.JS + Express 中做到這一點?

var util = require("util"),
    http = require("http");

var options = {
    host: "www.google.com",
    port: 80,
    path: "/"
};

var content = "";   

var req = http.request(options, function(res) {
    res.setEncoding("utf8");
    res.on("data", function (chunk) {
        content += chunk;
    });

    res.on("end", function () {
        util.log(content);
    });
});

req.end();

使用 node.js 您可以只使用 http.request 方法

http://nodejs.org/docs/v0.4.7/api/all.html#http.request

此方法內置在節點中,您只需要需要 http。

如果你只是想做一個 GET,那么你可以使用 http.get

http://nodejs.org/docs/v0.4.7/api/all.html#http.get

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/index.html'
};

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

(來自 node.js 文檔的示例)

你也可以使用 mikeal 的請求模塊

https://github.com/mikeal/request

簡單而高效的代碼:)

var request = require("request");

request(
    { uri: "http://www.sitepoint.com" },
    function(error, response, body) {
        console.log(body);
    }
);

文檔鏈接: https://github.com/request/request

喲可以試試 axios

var axios = require('axios');

axios.get("http://www.sitepoint.com", {
  headers: {
    Referer: 'http://www.sitepoint.com',
    'X-Requested-With': 'XMLHttpRequest'
  }
}).then(function (response) {
    console.log(response.data);
  });

暫無
暫無

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

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