蓝鸟承诺的 Cheerio 刮擦

Cheerio Scraping with Bluebird Promise

为什么这段代码不起作用?我得到

TypeError: $ is not a function

test.js

'use strict';

var Promise = require('bluebird');
var request = require('request-promise');
var cheerio = require('cheerio');

module.exports = {
    get: function () {

        return new Promise(function (resolve, reject) {
            var options = {
                uri: 'https://www.example.com',
                transorm: function (body) {
                    return cheerio.load(body);
                }
            };

            request(options)
                .then(function ($) {
                    // Error happens here
                    $('#mydivid').text();
                    resolve();
                })
                .catch(function (error) {
                    console.log(error);
                    reject(error);
                });
        });
    }
}

我再看了一下,发现了问题。您的 options 对象如下:

 var options = {
                uri: 'https://www.example.com',
                transorm: function (body) {
                    return cheerio.load(body);
                }
 };

您使用了 transorm 而不是 transform。因此它返回 html 内容的字符串而不是 cheerio.load(body)。将其更改为 transform 它会起作用。

 var options = {
                uri: 'https://www.example.com',
                transform: function (body) {
                    return cheerio.load(body);
                }
 };