Can I add more jquery selectors to cheerio? (node.

2019-06-03 02:18发布

问题:

I've been playing around with cheerio and I noticed it doesn't seem to support certain selectors specified in the jquery reference, specifically ":odd" and ":even". Is there a way to use these by importing the jquery package into my program? Or is that something that has to be implemented into the cheerio code?

Here's my code:

//var request = require('request');
var cheerio = require('cheerio');
var jquery = require('./jquery-1.10.2');

var fs = require('fs');

    $ = cheerio.load(fs.readFileSync('c:/java/bushkill_mls.html'));

    var odds = [];
    var evens = [];

    $('tr:odd').each(function() {
        odds = odds.concat($(this).text());

        });
        console.log(odds);

You can see I tried importing jquery but I couldn't get past importing it without getting the error "window is not defined" so obviously this seems like a node compatibility problem. So is there any way to increase the selector library in cheerio or maybe import another module that has the jquery selector functions I need?

回答1:

You can add something simple to cheerio like this:

var cheerio = require('cheerio');

cheerio.prototype.odd = function() {
    var odds = [];
    this.each(function(index, item) {
        if (index % 2 == 1) {
            odds.push(item);
        }
    });

    return cheerio(odds);
}

var $ = cheerio.load("<div>0</div><div>1</div><div>2</div><div>3</div><div>4</div>");
$("div").odd().each(function() {
    console.log($(this).text());
});

Yes, it doesn't match jquery exactly, but it's similar to how cheerio deals with jquery's :eq(n) selector.



回答2:

To answer the other part of your question :

import another module that has the jquery selector functions I need?

Whatever you can't do with cheerio, you can do with jsdom. It implements the full DOM and enables you to inject jQuery and other libraries.

As a downside, it slows down your code and takes a lot more memory, so it's better used only when no other alternative, eg: when you have more to do than simple html parsing.