使用IMPORTHTML无法导入网页表格中的球员图片与国旗,求解决方案
获取Sofifa squad页面的图片与数据解决方案
Google Sheets的IMPORTHTML确实只能提取表格的文本内容,无法直接获取图片URL。要拿到球员头像和国旗的图片链接,需要通过自定义Google Apps Script函数实现,具体步骤如下:
1. 打开Google Apps Script编辑器
在你的Google Sheets中,点击顶部菜单 扩展程序 > Apps 脚本,打开脚本编辑器。
2. 编写自定义抓取函数
替换编辑器里的默认代码为以下内容:
function getSofifaSquadWithImages(url, tableIndex = 1) { // 设置请求头,避免被网站反爬拦截 const options = { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36' } }; // 获取页面HTML内容 const response = UrlFetchApp.fetch(url, options); const html = response.getContentText(); // 匹配页面中的目标表格 const tableRegex = new RegExp(`<table[^>]*>([\\s\\S]*?)</table>`, 'g'); let tables = []; let match; while ((match = tableRegex.exec(html)) !== null) { tables.push(match[1]); } if (tableIndex - 1 >= tables.length) { return ['指定索引的表格不存在']; } const targetTable = tables[tableIndex - 1]; const rows = targetTable.match(/<tr[^>]*>([\\s\\S]*?)<\/tr>/g) || []; // 解析每一行的内容,提取文本和图片URL const result = rows.map(row => { const cells = row.match(/<td[^>]*>([\\s\\S]*?)<\/td>/g) || []; return cells.map(cell => { // 提取img标签的src属性 const imgMatch = cell.match(/<img[^>]*src="([^"]+)"/); if (imgMatch) { // 返回图片完整URL(Sofifa的图片是相对路径,需要补全域名) return `https://sofifa.com${imgMatch[1]}`; } else { // 提取纯文本内容 return cell.replace(/<[^>]+>/g, '').trim(); } }); }); return result; }
3. 保存并授权脚本
- 点击编辑器顶部的保存按钮,给脚本命名(比如
SofifaSquadScraper)。 - 首次运行函数时会弹出授权提示,按照指引完成授权(需要允许脚本访问外部网站和你的表格)。
4. 在表格中调用函数并显示图片
回到你的Google Sheets,在任意单元格输入:
=getSofifaSquadWithImages("https://sofifa.com/squad/1697556", 1)
函数会返回包含图片URL和文本数据的二维数组。要显示图片,只需在对应单元格使用IMAGE函数,比如:
=IMAGE(A2)
(假设A2是返回的图片URL单元格)
注意事项
- 如果遇到抓取失败,可能是Sofifa的反爬策略更新,可以尝试修改
User-Agent的值为当前浏览器的UA。 - 频繁抓取可能会被网站限制,建议不要短时间内多次调用函数。
内容的提问来源于stack exchange,提问作者Michael1509
相关产品推荐
相关产品推荐

