在JS中解析远程DOM

时间:2016-03-27 15:03:49

标签: javascript node.js dom

我希望获得远程网站的DOM并能够解析它,即理想情况下将解析后的结果转换为DOM节点,并有效地从中获取所需的元素,然后再处理它们。也就是说,我想从检索到的DOM中切片某些元素并将它们存储在数组中以进行进一步的操作。它真的可以实现吗? 到目前为止,我已经来了:

import request from 'request';

export default function getBody(url, callback) {
  request(url, (err, res, body) => {
    callback(body);
  });
}

在路线文件夹中:

import express from 'express';
import getBody from '../server';

const router = express.Router();

const url = 'http://www.google.com';
let result = {};

getBody(url, response => {
  result = response;
});

router.get('/', (req, res, next) => {
  res.render('index', { title: 'Express', data: result });
});

export default router;

此代码将远程页面的DOM放入我的视图中,但结果以巨型字符串形式返回,处理它将成为一场噩梦。我已尝试使用browser-request库从前端处理它,但我无法使标头工作,并且始终会返回错误No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

为了获得远程DOM并以上述方式解析它,最佳操作方法是什么?

1 个答案:

答案 0 :(得分:3)

如果您熟悉jQuery,可以使用cheerio来浏览DOM。

import request from 'request';
import cheerio from 'cheerio';

export default function getBody(url, callback) {
  request(url, (err, res, body) => {
    $ = cheerio.load(body);
    $('h2') // finds all of the `h2` tags within the `body` object.
  });
}