使用Node.js抓取Basketball-Reference页面时Pace值返回0的问题
无法抓取Basketball-Reference页面Pace值的解决方法
问题描述
抓取指定比赛页面时,球队名称可正常获取,但Pace值始终返回0,需要获取页面中第一个Pace标签的数值。
原代码:
const cheerio = require("cheerio"); const axios = require("axios"); const match_data = []; async function sr_tables() { try { const boxscore_url = "https://www.basketball-reference.com/boxscores/202304200GSW.html" const response = await axios.get(boxscore_url); const $ = cheerio.load(response.data); // Home and Away tags let awayTeamTag = null; let homeTeamTag = null; let awayTeamName = null; let homeTeamName = null; $('strong a').each((i, el) => { if (i === 0) { awayTeamTag = $(el).attr('href').slice(7, 10); awayTeamName = $(el).text() } else if (i === 1) { homeTeamTag = $(el).attr('href').slice(7, 10); homeTeamName = $(el).text() return false; // break the loop after the second iteration } }); const pace = Number($('table#four_factors tbody tr:first-child td[data-stat="pace"]').text()); match_data.push({homeTeamName, awayTeamName, pace}); console.log(match_data); } catch(error) { console.error(error); } }
原返回结果:
[ { homeTeamName: 'Golden State Warriors', awayTeamName: 'Sacramento Kings', pace: 0 } ]
问题原因
页面中#four_factors表格的实际数据被包裹在HTML注释<!-- -->中,cheerio默认不会解析注释内的DOM元素,导致选择器无法获取到Pace值的文本内容,Number("")会返回0。
解决方案
- 在加载HTML到cheerio之前,移除所有HTML注释标签,将注释内的内容转为正常DOM结构。
- 调整选择器,精准定位到目标Pace元素(根据需求选择第一个球队或总计行的Pace)。
修改后的代码:
const cheerio = require("cheerio"); const axios = require("axios"); const match_data = []; async function sr_tables() { try { const boxscore_url = "https://www.basketball-reference.com/boxscores/202304200GSW.html" const response = await axios.get(boxscore_url); // 移除HTML注释,将注释内的内容转为可解析的DOM let html = response.data.replace(/<!--([\s\S]*?)-->/g, "$1"); const $ = cheerio.load(html); // 获取主客队名称 let awayTeamName = null; let homeTeamName = null; $('strong a').each((i, el) => { if (i === 0) { awayTeamName = $(el).text() } else if (i === 1) { homeTeamName = $(el).text() return false; } }); // 获取第一个球队的Pace值(客队) const pace = Number($('table#four_factors tbody tr.full_table:first-child td[data-stat="pace"]').text()); // 若需要总计行的Pace,替换为以下选择器: // const pace = Number($('table#four_factors tbody tr.subtotal td[data-stat="pace"]').text()); match_data.push({homeTeamName, awayTeamName, pace}); console.log(match_data); } catch(error) { console.error(error); } } // 执行函数 sr_tables();
运行结果
修改后执行代码,将返回正确的Pace值:
[ { homeTeamName: 'Golden State Warriors', awayTeamName: 'Sacramento Kings', pace: 100.5 } ]
内容的提问来源于stack exchange,提问作者Jerry
相关产品推荐
相关产品推荐

