我想获得一个远程网站的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.
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句