How to use cheerio - 10 common examples

To help you get started, we’ve selected a few cheerio examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github postlight / mercury-parser / src / test-helpers.js View on Github external
after: done => {
      if (!has_fixtures && !cheerio.browser) {
        has_fixtures = nock.recorder.play();
        // eslint-disable-next-line no-console
        console.log(
          `This is disabled for browser/node interop. To capture fixutres,
          open ${'`src/test-helpers.js`'} and uncomment lines 58 and 59 and
          the fs import at top of file.`
        );
        // const text = `const nock = require('nock');\n${has_fixtures.join('\n')}`;
        // fs.writeFile(fp, text, done);
      } else {
        done();
      }
    },
  };
github matthewmueller / cheerio-select / test / select.element.js View on Github external
/**
 * Module dependencies.
 */
var $ = require('../'),
    _ = require('underscore'),
    parse = require('cheerio').parse,
    expect  = require('expect.js'),
    read = require('fs').readFileSync,
    helpers = require('./helpers'),
    t = helpers.t;

/*
 * Load test data
 */
var html = read(__dirname + '/fixtures/index.html'),
    dom  = parse(html);

/**
 * Mocha tests
 */
describe('select.element', function() {

  it('("*", dom) : should select all elements', function() {
    var elems = $('*', dom),
        nodeType = /tag|script|link/;

    // Select all
    expect(elems.length).to.be.above(30);

    // They should all be tags
    _.each(elems, function(elem) {
      expect(nodeType.test(elem.type)).to.be.ok();
github matthewmueller / cheerio-select / test / select.class.js View on Github external
it('(".e") : should find second classes', function() {
    var test = parse("<div><div class="test e"></div><div class="test"></div></div>");
    expect($(".e", test)).to.have.length(1);
    
    // Now add .e to second div and test again
    test.children[0].children[1].attribs['class'] = 'e';
    expect($(".e", test)).to.have.length(2);
  });
});
github matthewmueller / cheerio-select / test / helpers.js View on Github external
/**
 * Module dependencies.
 */
var $ = require('../'),
    _ = require('underscore'),
    parse = require('cheerio').parse,
    expect  = require('expect.js'),
    helpers = require('./helpers'),
    read = require('fs').readFileSync;

/* 
 * Load test data
 */
var html = read(__dirname + '/fixtures/index.html'),
    dom  = parse(html);

/*
 * Helper classes
 */

exports.ids = function(elem) {
  return elem.attribs.id;
};

exports.t = function(description, selector, ids, d) {
  it(description, function() {
    var result = $(selector, d || dom).map(exports.ids);
    expect(result).to.eql(ids);
  });
};
github matthewmueller / cheerio-select / test / select.name.js View on Github external
it('should handle complex insertions', function() {
    var a = cheerio('<div><a name="tName1" id="tName1ID">tName1 A</a><a name="tName2" id="tName2ID">tName2 A</a><div id="tName1">tName1 Div</div></div>');
    cheerio('#qunit-fixture').append(a);
    a = a.children();

    expect(a).to.have.length(3);
    expect(a[1].attribs.id).to.equal('tName2ID');

    // A little crazy.. basically test if new dom contains inserted elems
    expect($("[name=tName1]", cheerio.dom())[0]).to.equal(a[0]);
    expect($("[name=tName2]", cheerio.dom())[0]).to.equal(a[1]);
    expect($('#tName2ID', cheerio.dom())).to.have.length(1);

    a.remove();
  });
});
github algolia / react-instantsearch / functional-tests / utils.js View on Github external
return refinementsArray.map(refinementAsHTML =&gt; {
    // element is (simplified) <div>facetName <span>facetCount</span></div>
    const element = cheerio.parseHTML(refinementAsHTML)[0];

    // <div>**facetName** <span>facetCount</span></div>
    const name = element.firstChild.nodeValue.trim();

    // some widgets have no counts (pricesRanges)
    // <div>facetName <span>**facetCount**</span></div>
    const maybeCount = element.firstChild.nextSibling.children;

    return {
      name,

      count: maybeCount &amp;&amp; maybeCount[0] &amp;&amp; maybeCount[0].nodeValue !== undefined ?
        parseInt(maybeCount[0].nodeValue, 10) :
        'n/a'
    };
  });
github postlight / mercury-parser / src / test-helpers.js View on Github external
before: () => {
      if (cheerio.browser) return;
      if (!has_fixtures) {
        try {
          require(`../${fp}`); // eslint-disable-line global-require, import/no-dynamic-require, max-len
          has_fixtures = true;
        } catch (e) {
          nock.recorder.rec({
            dont_print: true,
          });
        }
      } else {
        has_fixtures = false;
        nock.recorder.rec({
          dont_print: true,
        });
      }
    },
github matthewmueller / cheerio-select / test / select.class.js View on Github external
/**
 * Module dependencies.
 */
var $ = require('../'),
    _ = require('underscore'),
    parse = require('cheerio').parse,
    expect  = require('expect.js'),
    read = require('fs').readFileSync,
    helpers = require('./helpers'),
    t = helpers.t;

/*
 * Load test data
 */
var html = read(__dirname + '/fixtures/index.html'),
    dom  = parse(html);

/**
 * Mocha tests
 */
describe('select.class', function() {
  t( "Class Selector", ".blog", ["mark","simon"] );
  t( "Class Selector", ".GROUPS", ["groups"] );
  t( "Class Selector", ".blog.link", ["simon"] );
  t( "Class Selector w/ Element", "a.blog", ["mark","simon"] );
  t( "Parent Class Selector", "p .blog", ["mark","simon"] );

  t('("p .blog") : should find elements within class', 'p .blog', ['mark', 'simon']);

  // No support for UTF8 yet...
  t( "Class selector using UTF8", ".台北Táiběi", ["utf8class1"] );
  t( "Class selector using UTF8", ".台北", ["utf8class1","utf8class2"] );
github msavy / gitbook-plugin-asciidoc-admonition-icons / index.js View on Github external
page.sections.forEach((section) =&gt; {
                if (section == undefined || section.content == undefined) {
                    return true;
                }
                $ = cheerio.load(section.content);
                // Find asciidoc admonition block.
                $(".admonitionblock").each(function () {
                    $this = $(this);
                    // Look at classes, should include the admonition type along with other irrelevant stuff.
                    candidateClasses = $(this)[0].attribs.class.split(/\s+/);
                    // Find the admonition class
                    admonClass = candidateClasses.find(klazz =&gt; options[klazz]);
                    // Skip if no relevant candidate found
                    if (admonClass === undefined) {
                        return true;
	    	        }
                    // Admonishment
                    admon = options[admonClass];
                    // Replacement we'll sub in.
                    iconElem = $("<div></div>")
                        .addClass(admon.classes)
github JpEncausse / WSRNodeJS / plugins / dictionary / dictionary.js View on Github external
var parse = function(html, word){
  var $ = require('cheerio').load(html);
  var ok = false;
  
  $('#TableHTMLResult .ldcomIN').each(function(){
    var value = $(this).text().trim();
    var match = matcher(value); 
    
    // console.log('['+value+']', 'match=', match, 'ok=', ok);
    if (ok && !match){ ok = value;   return false; } // Break loop
    if (match){        ok = value; // Will take next value 
      if (value.indexOf(word) == 0){ return false; }
    }
  });
  return ok;
}