是否有可能在服务器端使用Node.js使用jQuery选择器/DOM操作?
当前回答
您必须使用新的JSDOM API来获取窗口。
const jsdom = require("jsdom");
const { window } = new jsdom.JSDOM(`...`);
var $ = require("jquery")(window);
其他回答
我的工作代码是:
npm install jquery
然后:
global.jQuery = require('jquery');
global.$ = global.jQuery;
或者如果窗口存在,则:
typeof window !== "undefined" ? window : this;
window.jQuery = require('jquery');
window.$ = window.jQuery;
据我所知没有。DOM是一个客户端的东西(jQuery不解析HTML,但解析DOM)。
下面是一些当前的Node.js项目:
https://github.com/ry/node/wiki (https://github.com/nodejs/node)
SimonW的djangode非常酷…
一个使用Cheerio的简单爬虫程序
这是我在Node.js中制作一个简单爬虫程序的公式。这是想要在服务器端进行DOM操作的主要原因,也可能是这里的原因。
首先,使用request下载要解析的页面。下载完成后,将其处理为cheerio,并像使用jQuery一样开始DOM操作。
工作的例子:
var
request = require('request'),
cheerio = require('cheerio');
function parse(url) {
request(url, function (error, response, body) {
var
$ = cheerio.load(body);
$('.question-summary .question-hyperlink').each(function () {
console.info($(this).text());
});
})
}
parse('http://stackoverflow.com/');
这个例子将打印到控制台的所有顶级问题显示在SO主页。这就是为什么我喜欢Node.js和它的社区。没有比这更容易的了:-)
安装的依赖关系:
NPM安装请求
然后运行(假设上面的脚本在爬虫.js文件中):
节点crawler.js
编码
有些页面会有某种编码的非英语内容,您需要将其解码为UTF-8。例如,巴西葡萄牙语(或任何其他起源于拉丁语的语言)的页面可能会被编码为ISO-8859-1(也就是ISO-8859-1)。“latin1”中的一个)。当需要解码时,我告诉request不要以任何方式解释内容,而是使用iconv-lite来完成工作。
工作的例子:
var
request = require('request'),
iconv = require('iconv-lite'),
cheerio = require('cheerio');
var
PAGE_ENCODING = 'utf-8'; // change to match page encoding
function parse(url) {
request({
url: url,
encoding: null // do not interpret content yet
}, function (error, response, body) {
var
$ = cheerio.load(iconv.decode(body, PAGE_ENCODING));
$('.question-summary .question-hyperlink').each(function () {
console.info($(this).text());
});
})
}
parse('http://stackoverflow.com/');
运行之前,安装依赖项:
NPM安装请求iconv-lite
最后:
节点crawler.js
下面的链接
下一步是跟踪链接。假设你想在SO上列出每个顶级问题的所有海报。您必须首先列出所有主要问题(如上例),然后进入每个链接,解析每个问题的页面以获得涉及的用户列表。
当您开始跟踪链接时,回调地狱就开始了。为了避免这种情况,你应该使用一些承诺,未来或其他东西。我总是在我的工具带中保持异步。下面是一个使用async的爬虫的完整示例:
var
url = require('url'),
request = require('request'),
async = require('async'),
cheerio = require('cheerio');
var
baseUrl = 'http://stackoverflow.com/';
// Gets a page and returns a callback with a $ object
function getPage(url, parseFn) {
request({
url: url
}, function (error, response, body) {
parseFn(cheerio.load(body))
});
}
getPage(baseUrl, function ($) {
var
questions;
// Get list of questions
questions = $('.question-summary .question-hyperlink').map(function () {
return {
title: $(this).text(),
url: url.resolve(baseUrl, $(this).attr('href'))
};
}).get().slice(0, 5); // limit to the top 5 questions
// For each question
async.map(questions, function (question, questionDone) {
getPage(question.url, function ($$) {
// Get list of users
question.users = $$('.post-signature .user-details a').map(function () {
return $$(this).text();
}).get();
questionDone(null, question);
});
}, function (err, questionsWithPosters) {
// This function is called by async when all questions have been parsed
questionsWithPosters.forEach(function (question) {
// Prints each question along with its user list
console.info(question.title);
question.users.forEach(function (user) {
console.info('\t%s', user);
});
});
});
});
跑步前:
NPM安装请求异步
运行一个测试:
节点crawler.js
样例输出:
Is it possible to pause a Docker image build?
conradk
Thomasleveil
PHP Image Crop Issue
Elyor
Houston Molinar
Add two object in rails
user1670773
Makoto
max
Asymmetric encryption discrepancy - Android vs Java
Cookie Monster
Wand Maker
Objective-C: Adding 10 seconds to timer in SpriteKit
Christian K Rider
这是你应该知道的基本开始制作你自己的爬虫:-)
库的使用
请求 iconv-lite 恭喜恭喜 异步
2016年,事情就简单多了。使用控制台将jquery安装到node.js:
npm install jquery
将它绑定到node.js代码中的变量$(例如-我习惯了它):
var $ = require("jquery");
做的东西:
$.ajax({
url: 'gimme_json.php',
dataType: 'json',
method: 'GET',
data: { "now" : true }
});
也适用于gulp,因为它基于node.js。
模块jsdom是一个很棒的工具。但如果你想评估整个页面,并在服务器端做一些奇怪的事情,我建议在它们自己的上下文中运行它们:
vm.runInContext
所以像require / CommonJS这样的东西不会破坏你的Node进程本身。
你可以在这里找到相关文档。干杯!