使用Cheerio抓取击剑排名时数据合并问题求助
解决Cheerio爬取击剑排名数据时的文本合并问题
问题核心是你直接调用row.text()会把所有匹配到的.ranking:not(:has(div))元素的文本拼接在一起,导致排名、积分、T-P的数据合并成一串。要拆分数据,你需要逐个提取每个td元素的文本,然后按需保留或丢弃对应字段。
修改后的代码如下:
async function performScraping() { const axiosResponse = await axios.request({ method: "GET", url: "https://fencing.ophardt.online/en/show-ranking/html/60198", headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36", }, }); const $ = cheerio.load(axiosResponse.data); const rows = $(".rankingbody > tbody > tr").toArray(); for (const row of rows) { // 获取包含排名、积分、T-P的三个td元素 const dataColumns = $(row).find(".ranking:not(:has(div))").toArray(); // 获取选手名称 const name = $(row).find(".ranking > .btn-group > a").text().trim(); // 提取排名(第一个td)、积分(第二个td),跳过第三个T-P的td const rank = $(dataColumns[0]).text().trim(); const points = $(dataColumns[1]).text().trim(); console.log(`选手:${name}`); console.log(`排名:${rank},积分:${points}`); console.log("---"); } } performScraping();
关键改动说明:
- 将获取到的td元素转为数组
dataColumns,通过索引逐个访问每个字段对应的元素 - 使用
trim()替代replace(/\s\s+/g, " "),更简洁地去除文本前后的多余空格 - 明确通过索引提取排名(第0位)和积分(第1位),直接忽略第2位的T-P数据
- 调整输出格式,让结果更清晰易读
内容的提问来源于stack exchange,提问作者SoggyMould
相关产品推荐
相关产品推荐

