【发布时间】:2021-05-18 15:04:07
【问题描述】:
我正在尝试从 wikipedia 中抓取 HTML 表格以获取数据,但是由于 rowspan 属性,我在遍历表格时遇到了很多麻烦。我正在使用cheerio 包并且迷失在cheerio 返回的jQuery 对象的数量中。任何帮助将不胜感激,我已经为此努力了好几天。您在下面看到的只是我尝试使用的代码的一小部分。谢谢
表格 URL = "https://en.wikipedia.org/wiki/Stephen_King_bibliography"
const axios = require("axios");
const $ = require("cheerio");
const WIKI_URL = "https://en.wikipedia.org/wiki/Stephen_King_bibliography";
const getBooks = async (url) => {
const scrapedBooks = [];
try {
const res = await axios.get(url);
const htmlParse = $(
"#mw-content-text > div.mw-parser-output > table:nth-child(6) > tbody > tr",
res.data
);
// let filtData = [];
// for (let i = 0; i < htmlParse.length; i++) {
// filtData.push(
// htmlParse[i].children.filter((child) => child.data !== "\n")
// );
// }
// htmlParse[i].children[5].attribs["rowspan"]
//Getting the Row headers
let headers = [];
htmlParse.each((index, el) => {
headers.push(
$(el)
.find("th")
.text()
.split("\n")
.filter((item) => item.length)
);
});
headers = headers[0];
let data = [];
htmlParse.each((index, el) => {
let item = $(el).find("td");
item.attr("rowspan") ? data.push(item.get()) : data.push("NOT FOUND");
});
console.log(data);
} catch (err) {
console.log(err);
}
};
getBooks(WIKI_URL);
【问题讨论】:
-
rowspan 是一个范围,每行推送相同的数据并减去
标签: javascript html sorting cheerio