简体   繁体   English

在 Node.js / Express 中,我如何“下载”页面并获取其 HTML?

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

Inside the code, I want to download "http://www.google.com" and store it in a string.在代码中,我想下载“http://www.google.com”并将其存储在一个字符串中。 I know how to do that in urllib in python.我知道如何在 python 的 urllib 中做到这一点。 But how do you do it in Node.JS + Express?但是你如何在 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();

Using node.js you can just use the http.request method使用 node.js 您可以只使用 http.request 方法

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

This method is built into node you just need to require http.此方法内置在节点中,您只需要需要 http。

If you just want to do a GET, then you can use http.get如果你只是想做一个 GET,那么你可以使用 http.get

http://nodejs.org/docs/v0.4.7/api/all.html#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);
});

(Example from node.js docs) (来自 node.js 文档的示例)

You could also use mikeal's request module你也可以使用 mikeal 的请求模块

https://github.com/mikeal/request https://github.com/mikeal/request

Simple short and efficient code :)简单而高效的代码:)

var request = require("request");

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

doc link: https://github.com/request/request文档链接: https://github.com/request/request

Yo can try with axios哟可以试试 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