[英]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 的請求模塊
簡單而高效的代碼:)
var request = require("request");
request(
{ uri: "http://www.sitepoint.com" },
function(error, response, body) {
console.log(body);
}
);
喲可以試試 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.