是否有可能在服务器端使用Node.js使用jQuery选择器/DOM操作?


当前回答

我相信这个问题的答案是肯定的。 https://github.com/tmpvar/jsdom

var navigator = { userAgent: "node-js" };  
var jQuery = require("./node-jquery").jQueryInit(window, navigator);

其他回答

jQuery模块可以通过以下方式安装:

npm install jquery

例子:

var $ = require('jquery');
var http = require('http');

var options = {
    host: 'jquery.com',
    port: 80,
    path: '/'
};

var html = '';
http.get(options, function(res) {
res.on('data', function(data) {
    // collect the data chunks to the variable named "html"
    html += data;
}).on('end', function() {
    // the whole of webpage data has been collected. parsing time!
    var title = $(html).find('title').text();
    console.log(title);
 });
});

jQuery在Node.js中的引用**:

http://quaintous.com/2015/07/31/jqery-node-mystery/ http://www.hacksparrow.com/jquery-with-node-js.html

我相信这个问题的答案是肯定的。 https://github.com/tmpvar/jsdom

var navigator = { userAgent: "node-js" };  
var jQuery = require("./node-jquery").jQueryInit(window, navigator);

一个使用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 恭喜恭喜 异步

在写这篇文章的时候,也有保持的Cheerio。

快速,灵活,精益的实现核心jQuery设计 特别是针对服务器。

警告

这个解决方案,正如Golo Roden提到的是不正确的。它只是一个快速修复,帮助人们使用Node应用程序结构运行实际的jQuery代码,但它不是Node哲学,因为jQuery仍然运行在客户端,而不是在服务器端。我很抱歉给了一个错误的答案。


您还可以使用节点渲染Jade,并将jQuery代码放在其中。下面是jade文件的代码:

!!! 5
html(lang="en")
  head
    title Holamundo!
    script(type='text/javascript', src='http://code.jquery.com/jquery-1.9.1.js')
  body
    h1#headTitle Hello, World
    p#content This is an example of Jade.
    script
      $('#headTitle').click(function() {
        $(this).hide();
      });
      $('#content').click(function() {
        $(this).hide();
      });