【发布时间】:2021-10-02 05:21:40
【问题描述】:
我只是从 HTML(我不是网络开发人员)和 web.xml 开始。我正在尝试获取 html 文档中的标签列表,但我得到了TypeError: dom.getElementsByTagName is not a function。
我使用axios 发出get 请求,然后使用cheerio 将response.data 加载到我调用getElementsByTagName 方法的html 文档中。
我错过了加载一些模块还是我做错了什么?
一如既往地感谢您的帮助。
这是我的方法:
const db = require("../config/database");
const axios = require('axios');
const jsdom = require('jsdom');
const{JSDOM} = jsdom;
const cheerio = require('cheerio');
// const Route = require('../schemas/route');
const apiKey = process.env.API_KEY;
exports.ingest = async(req, res) => {
const {url} = req.query;
const response = await axios.get(url); // Property 'get' does not exist on type 'typeof import("/Volumes/ProjectsSSD/FixitServer/fixit_server_node/node_modules/axios/index")' but it does makje the request..??
// console.log('response is: ', response);
if (response.status == 200){
const document = cheerio.load(response.data, {decodeEntities: true}, false).html();
// const document = cheerio.load(response.data, {decodeEntities: false}, true);
console.log(' #################### response.data is: \n\n ', document);
// var tag = document.createElement("div"); // TypeError: document.createElement is not a function
// tag.innerHTML = str;
// var t = tag.getElementsByTagName("*");
// var ele = [];
// for (var i = 0; i < t.length; i++) {
// ele.push(t[i].tagName);
// }
// console.log('tags are: ', ele);
const dom = new JSDOM(document);
console.log(' @@@@@@@@@@@@@@@@@@@@ dom is: \n\n', dom);
const tags = document.getElementsByTagName('*'); // TypeError: dom.getElementsByTagName is not a function
console.log('tags are: ', tags);
} else{
res.status(response.status).send(response.statusText);
}
};
【问题讨论】:
-
错误信息与代码不匹配。该代码使用
document,而不是dom,但它从不声明该变量。 -
是检查状态码后的第一行:
const document = cheerio.load(response.data, {decodeEntities: true}, false).html(); -
错误消息显示
dom.getElementsByTagName。为什么它发生在包含document.getElementsByTagName的行上? -
根据例子here我觉得应该是
dom.window.document.getElementsByTagName -
确实如此。没错,它适用于dom。如果您想将其作为答案,我将很乐意接受。非常感谢。
标签: javascript node.js cheerio