【问题标题】:How can I automatically populate a cell in Google Sheets with an image from a Pinterest page?如何使用 Pinterest 页面中的图像自动填充 Google 表格中的单元格?
【发布时间】:2020-02-19 19:43:27
【问题描述】:

假设我有一个 Google 表格,其中包含 B 列中 Pinterest 上各个图钉的 URL。例如:https://www.pinterest.com/pin/146578162860144581/

我想用 B 列中 URL 中的主图像填充 C 列中的单元格。

目前我必须手动执行此操作,方法是单击 B 列中的 URL,复制图像 URL,然后将图像插入 C 列的单元格中。

有没有办法自动化这个?

【问题讨论】:

    标签: google-sheets


    【解决方案1】:

    解决方案

    是的,您可以使用工作表的 Google Apps 脚本来实现此目的。在以下代码段下方,您可以找到有关其工作原理的简要说明。

    代码

    function populateImage() {  
      var sheet = SpreadsheetApp.getActiveSheet();
      // Get cell values of your link column
      var values = sheet.getRange('B1:B5').getValues();
      // Range where we want to insert the images
      var imgrange = sheet.getRange('C1:C5');
      
      for (i=0;i<5;i++){
        // Cell we want to insert the image
        var cell = imgrange.getCell(i+1, 1);
        
        // Pin Id which is at the end of each url provided, in this case 146578162860144581
        var number = values[i][0].substring(29,values[i][0].length-1);
        
        // Url to make the fetch request to access the json of that pin
        var url = 'https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids='+number;
        var response = UrlFetchApp.fetch(url);
        var json = response.getContentText();
        var data =  JSON.parse(json);
        
        // Url of the image of the pin
        var imgurl =data.data[0].images["237x"].url;
    
        // Insert image from url
        cell.setFormula('=image("'+imgurl+'")');
      }
    
    }

    结果

    说明

    要在工作表的网站中插入图片,您需要图片网址。这是这个问题中最棘手的部分。 Pinterest 没有提供一个很好的方法来获取这个图像 url,只需要获取 pin url,因为这个请求将返回 HTML 数据而不是 json。为此,您需要向此 url https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=PINIDNUMBER 发出获取请求。您可以在 this Stack Overflow question 中找到更多相关信息,感谢 @SambhavSharma。

    当您按照此 url 获取时,您将获得 pin 的 json,您可以从中检索所需的图像 url(除了有关此 pin 的许多其他数据)。有了它,您可以简单地将其插入下一列。

    我希望这对您有所帮助,如果您需要其他任何内容或有什么不明白的地方,请告诉我。

    【讨论】:

    • 首先,感谢您的帮助。对此,我真的非常感激。当我运行这个脚本时,我收到错误TypeError: Cannot read property '237x' of undefined (line 22, file "Code")
    猜你喜欢
    • 2022-01-08
    • 2020-12-29
    • 2022-11-23
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2015-09-09
    • 2017-05-01
    • 2020-03-25
    相关资源
    最近更新 更多