例如parse5。解析函数返回文档。但是,querySelector函数并不存在。https://developer.mozilla.org/en-US/docs/Web/API/Document。
import fetch from 'node-fetch';
import { parse } from 'parse5';
(async () => {
const options = {
redirect: "manual"
};
const response = await fetch('https://google.com', options);
const dom = parse(await response.text());
console.log(dom.querySelector('title'));
})();发布于 2021-05-19 01:27:21
我不确定,但我认为Node.JS没有针对querySelector的实现。
您可以使用polyfill来解决这个问题,比如this implementation at Github
/**
* Polyfills the querySelector and querySelectorAll methods.
* @see https://gist.github.com/Fusselwurm/4673695
*/
(function () {
var style;
var select = function (selector, maxCount) {
var all = document.all,
l = all.length,
i,
resultSet = [];
style.addRule(selector, "foo:bar");
for (i = 0; i < l; i += 1) {
if (all[i].currentStyle.foo === "bar") {
resultSet.push(all[i]);
if (resultSet.length > maxCount) {
break;
}
}
}
style.removeRule(0);
return resultSet;
};
if (document.querySelectorAll || document.querySelector) {
return;
}
style = document.createStyleSheet();
document.querySelectorAll = document.body.querySelectorAll = function (selector) {
return select(selector, Infinity);
};
document.querySelector = document.body.querySelector = function (selector) {
return select(selector, 1)[0] || null;
};
}());Polyfills帮助提供对NodeJS的浏览器支持和实现。您可以对其他函数使用相同的技术(例如,在React应用程序中支持IE7中不存在的函数)。
备注:也可以使用npm包,see https://www.npmjs.com/package/polyfill-queryselector
发布于 2021-12-03 00:40:27
parse函数返回的对象称为文档,但它与您在浏览器中找到的Web API文档不同。相反,它是一个非常简单的树数据结构的根。有关此数据结构的文档位于https://github.com/inikulin/parse5/blob/master/packages/parse5/docs/tree-adapter/default/interface-list.md
尽管该树很简单,但它包含了解析文档所需的所有内容。很可能你将不得不递归地搜索你正在寻找的元素。以下面的代码为例:
const fetch = require('node-fetch');
const { parse } = require('parse5');
const getDescendantByTag = (node, tag) => {
for (let i = 0; i < node.childNodes?.length; i++) {
if (node.childNodes[i].tagName === tag) return node.childNodes[i];
const result = getDescendantByTag(node.childNodes[i], tag);
if (result) return result;
}
return null;
};
fetch('https://google.com', { redirect: 'manual' })
.then((response) => response.text())
.then((text) => {
console.log(getDescendantByTag(parse(text), 'title'));
});https://stackoverflow.com/questions/67591100
复制相似问题