javascript - Sharing variable scope with jsdom and jquery in Node -
So, I was writing a simple page scraper with jsdom and jquery, and ran into a problem I'm not sure How to solve that
Here is some code that works (URL changes):
var jsdom = need ("jsdom"); Var FS = Requirement ('FS'); Var jquery = fs.readFileSync (".js / jquery-min.js"). ToString (); // Product has two pages, here page 1 jsdom.env ({url: 'http://exampleshoppingpage.com', src: [jquery], done: function (error, window) {var $ = window. $; $ ('.product .product .title a'). Each (function () {console.log ($ (this) .text ());});}}); // page2jsdom.env ({url: 'http://exampleshoppingpage.com?page=2', src: [jquery], done: do the exact thing for function (error, window) {var $ = window $. ($ .products list .Product .title a '). Each (function () {console.log ($ (this) .text ());});}});
But what I really want to do, all these products should be obtained and they need to sort them before printing. Here's what I've tried:
var jsdom = need ("jsdom"); Var FS = Requirement ('FS'); Var jquery = fs.readFileSync (".js / jquery-min.js"). ToString (); Var products = []; // Product has two pages, here page 1 jsdom.env ({url: 'http://exampleshoppingpage.com', src: [jquery], done: function (error, window) {var $ = window. $; Products $ ('Manufacturer Manufacturer.' Title One). Each (function () {products.push ($ (this) .text ());});}}); // page2jsdom.env ({url: 'http://exampleshoppingpage.com?page=2', src: [jquery], done: do the exact same function (error, window) {var $ = window $ ($ .products list .product .title a '). Each (function () {products.push ($ (this) .text ());});}}); Products = products.sort (); Console.log (products.join ("\ n"));
I get an empty array I have tried some other ways to determine whether I was just doing something stupid. I am thinking that the external part of this program Is there nothing to do with JSID?
This is a case where we have to remember to think asynchronously. Your scope is fine, but you are trying to dump the console products
before it comes with data.
In addition, Array.prototype.sort ()
. It does not return an array
var jsdom = need ("jsdom"); Var jquery = "http://code.jquery.com/jquery.js"; Var products = []; // page 1 jsdom.env ({url: 'http://news.ycombinator.com/', script: [jquery], done: function (error, window) {var $ = window. $; $ ('Td .title: not (: last) a) Every (function () {products.push ($ (this) .text ());}); // page 2 jsdom.env ({url: 'https: / / News.ycombinator.com/news?p=2 ', script: [jquery], done: function (error, window) {var $ = window. $; $ (' Td.title: no (: last) one ') .eitch (function () (products.push ($ (this) .text ());}); products.sort (); console.log (products);}});}});
Comments
Post a Comment