How to use JQuery selectors in Node.js

后端 未结 4 1535
梦谈多话
梦谈多话 2021-02-06 05:16

I\'m trying to extract email info from HTML files in my hard drive.

If I load the file in firefox and run jQuerify bookmarklet I can use successfully the following selec

4条回答
  •  猫巷女王i
    2021-02-06 05:40

    I now know what the problem is.

    The html data, must be passed in the document creation call, so the code look like this:

    var jsdom = require("jsdom"),
        fs = require('fs');
    
    fs.readFile('file_1.html', 'utf-8', function(err, data){
      if (err) {
        throw err;
      }
    
      // This output the document
      //console.log(data)
    
      // HTML data should be in document creation call
      var document = jsdom.jsdom(data); // data is the html content
      var script = document.createElement("script");
    
      // HTML data SHOULD NOT be in window creation call
      var window = document.createWindow();
    
      script.src = 'http://code.jquery.com/jquery-1.4.2.js';
      script.onload = function() {
        console.log(window.jQuery.fn.jquery);
        // outputs: 1.4.2
        //console.log(window.jQuery);
    
        /*
         * This line works if i load the local file in firefox and execute
         * the jQuerify bookmarlet
         */
        window.jQuery("a.iEmail").each(function(el) {
          console.log(window.jQuery(this).attr('href'))
        });
      };
      document.head.appendChild(script);
    });
    

提交回复
热议问题