所以,我正在使用 jsdom 和 jquery 编写一个简单的页面抓取工具,并遇到了一个我不确定如何解决的问题。
这里有一些有效的代码(更改了 URL):
var jsdom = require("jsdom");
var fs = require('fs');
var jquery = fs.readFileSync("./js/jquery-min.js").toString();
//There's two pages of product, here's page 1
jsdom.env({
url: 'http://exampleshoppingpage.com',
src: [ jquery ],
done: function(error, window){
var $ = window.$;
$('.productlist .product .title a').each(function() {
console.log($(this).text());
});
}
});
//And do the exact same thing for page 2
jsdom.env({
url: 'http://exampleshoppingpage.com?page=2',
src: [ jquery ],
done: function(error, window){
var $ = window.$;
$('.productlist .product .title a').each(function() {
console.log($(this).text());
});
}
});
但我真正想做的是获取所有这些产品并在打印之前对其进行分类。这是我尝试过的:
var jsdom = require("jsdom");
var fs = require('fs');
var jquery = fs.readFileSync("./js/jquery-min.js").toString();
var products = [];
//There's two pages of product, here's page 1
jsdom.env({
url: 'http://exampleshoppingpage.com',
src: [ jquery ],
done: function(error, window){
var $ = window.$;
products $('.productlist .product .title a').each(function() {
products.push($(this).text());
});
}
});
//And do the exact same thing for page 2
jsdom.env({
url: 'http://exampleshoppingpage.com?page=2',
src: [ jquery ],
done: function(error, window){
var $ = window.$;
$('.productlist .product .title a').each(function() {
products.push($(this).text());
});
}
});
products = products.sort();
console.log (products.join("\n"));
我得到一个空数组。我尝试了一些其他方法来确定我是否只是做了一些愚蠢的事情。我假设它与 jsdom 中的 jQuery 不与程序外部共享范围有关?
最佳答案
在这种情况下,我们必须记住异步思考。您的范围很好,但您试图在填充数据之前将 products
转储到控制台。
此外,Array.prototype.sort()
operates on the array directly 。它不返回数组。
var jsdom = require("jsdom");
var jquery = "http://code.jquery.com/jquery.js";
var products = [];
// page 1
jsdom.env({
url: 'http://news.ycombinator.com/',
scripts: [ jquery ],
done: function(error, window){
var $ = window.$;
$('td.title:not(:last) a').each(function() {
products.push( $(this).text() );
});
// page 2
jsdom.env({
url: 'https://news.ycombinator.com/news?p=2',
scripts: [ jquery ],
done: function(error, window){
var $ = window.$;
$('td.title:not(:last) a').each(function() {
products.push( $(this).text() );
});
products.sort();
console.log( products );
}
});
}
});
关于javascript - 在 Node 中与 jsdom 和 jquery 共享变量范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26739854/