在JS中解析远程DOM

Parse remote DOM in JS

本文关键字:DOM JS      更新时间:2023-09-26

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

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

在routes文件夹中:

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输入到我的视图中,但结果是一个巨大的字符串,处理它将是一场噩梦。我曾尝试使用浏览器请求库从前端处理它,但我无法使标题工作,它总是返回错误No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

为了获得远程DOM并以上面描述的方式解析它,最好的做法是什么?

如果您熟悉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.
  });
}