如何将SoccerStats特定表格稳定导入Google Sheets
解决Google Sheets中稳定提取指定表格的方案
方法一:使用IMPORTXML结合动态XPath定位
直接通过XPath根据表格标题文本定位目标表格,而非依赖固定单元格位置,能大幅降低页面格式变动的影响。
示例公式
根据页面实际的标题文本调整(比如页面是英文用Home Last 4,中文用主场近4场):
=IMPORTXML("https://www.soccerstats.com/formtable.asp?league=england", "//*[contains(text(), 'Home Last 4')]/following-sibling::table[1]")
如果知道标题的具体标签(比如是<h3>),可以进一步缩小范围,提升准确性:
=IMPORTXML("https://www.soccerstats.com/formtable.asp?league=england", "//h3[contains(text(), 'Home Last 4')]/following-sibling::table[1]")
原理
XPath的contains(text(), '目标文本')会匹配所有包含指定文本的元素,following-sibling::table[1]则取该元素之后的第一个表格,只要页面中表格标题的核心文本不变,就能稳定提取表格数据。
方法二:用Google Apps Script实现更灵活的提取
如果页面结构变动较大(比如标题和表格之间插入了其他元素),脚本可以通过DOM解析精准定位,适配更多场景。
示例脚本
function importHomeLast4Table() { const targetSheetName = "主场近4场"; const url = "https://www.soccerstats.com/formtable.asp?league=england"; const targetTitle = "Home Last 4"; // 根据页面实际文本修改 // 获取网页内容并解析为DOM const response = UrlFetchApp.fetch(url); const html = response.getContentText(); const dom = new DOMParser().parseFromString(html, 'text/html'); // 定位包含目标标题的元素 const titleElement = Array.from(dom.querySelectorAll('h3, h4, td, div')) .find(el => el.textContent.trim().includes(targetTitle)); if (!titleElement) { SpreadsheetApp.getUi().alert("未找到目标表格标题"); return; } // 遍历找到标题后的第一个表格 let tableElement = titleElement.nextElementSibling; while (tableElement && tableElement.tagName !== 'TABLE') { tableElement = tableElement.nextElementSibling; } if (!tableElement) { SpreadsheetApp.getUi().alert("未找到目标表格"); return; } // 提取表格数据 const rows = Array.from(tableElement.querySelectorAll('tr')); const tableData = rows.map(row => { return Array.from(row.querySelectorAll('td, th')).map(cell => cell.textContent.trim()); }); // 写入工作表 const ss = SpreadsheetApp.getActiveSpreadsheet(); let sheet = ss.getSheetByName(targetSheetName); if (!sheet) sheet = ss.insertSheet(targetSheetName); sheet.clearContents(); sheet.getRange(1, 1, tableData.length, tableData[0].length).setValues(tableData); }
使用步骤
- 打开你的Google表格,点击
扩展程序 > Apps 脚本 - 粘贴上述代码,修改
targetTitle为页面实际的标题文本(比如中文的主场近4场) - 保存并运行脚本,首次运行需要授权
- 可以设置定时触发器(在脚本编辑器的
编辑 > 当前项目的触发器),实现自动更新
优势
脚本不依赖固定的单元格位置,只要标题文本不变,哪怕页面插入广告、调整布局,依然能找到目标表格,稳定性远高于单元格引用。
内容的提问来源于stack exchange,提问作者William Savage
相关产品推荐
相关产品推荐

