【发布时间】:2021-11-27 21:24:11
【问题描述】:
这是我第一次尝试学习如何从网络上抓取图像并将其粘贴到 Google 表格中。我想从https://ir.eia.gov/ngs/ngs.html 下载第二张图片并将其粘贴到 Google 表格中。在网络上,有两个图像。我想获得 下的第二张图像。我喜欢学习如何在代码中引用它的 img alt= 或 src="ngs.gif" 而不是索引,因此我也可以将这个概念用于其他各种 HTML 情况。任何人都可以帮助修复以下代码以便我学习吗?谢谢!
function test() {
const url = 'https://ir.eia.gov/ngs/ngs.html';
const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
var $ = Cheerio.load(res);
// I want to download the image, <img alt="Working Gas in Underground Storage Compared with Five-Year Range" src="ngs.gif" border="0">
// What should be changed in the following code?
var chart = $('img').attr('src').find('ngs.gif');
SpreadsheetApp.getActiveSheet().insertImage(chart, 1, 1);
}
【问题讨论】:
-
Cheerio 似乎无法做到这一点,因为它只会返回
src的文件名,而不是ngs.gif图像文件的完整源路径链接。您需要使用 getBlob() 将ngs.gif图像的实际源路径 URL 作为 blob 获取,然后您可以轻松地将其作为图像插入到工作表中。
标签: image google-apps-script web-scraping cheerio