TypeScript 使用cheerio抓取数据如何正确格式化为对象数组
问题成因
你选择的遍历节点层级错误:$("#teamDetails > div.memberList") 匹配到的是整个成员列表的父容器,正常页面中该容器全局只有1个,因此map循环实际只执行1次。cheerio调用.text()方法时,会自动拼接当前选中节点下所有匹配子元素的文本,最终就得到了所有成员名称拼接的结果。
修复方案
直接将遍历的节点改为单个成员节点,同时调整对应查找逻辑即可,修复后完整代码如下:
export {}; const cheerio = require("cheerio"); const fetch = require("isomorphic-fetch"); interface PlayerStats { name: string; role: string; score: string; matches: string; totalBattles: number; } const fetchData = async (faction: string) => { // 原请求地址端口前符号错误,已修正为冒号 const req = await fetch("https://localhost:3000/" + faction); const data: string = await req.text(); const $ = cheerio.load(data); // 直接选中所有单个成员节点作为遍历对象 const memberElements: Element[] = $("#teamDetails > div.memberList .member").toArray(); const playerStats: PlayerStats[] = memberElements.map((el: Element) => { // el本身就是单个.member节点,无需额外加.member层级查找 const name: string = $(el).find(".name p").text() || ""; const score: string = $(el).find(".stats .battlesWon").text(); const matches: string = $(el).find(".stats .matchesPlayed").text(); const role: string = $(el).find(".specialty h6").text(); const totalBattles: number = parseInt(matches) * 3; return { name, score, matches, role, totalBattles }; }); console.log(playerStats[0]); return playerStats; }; fetchData("9a7059e278");
内容的提问来源于stack exchange,提问作者Liiaam93
相关产品推荐
相关产品推荐

