假设我有一个谷歌工作表,在B列中包含指向Pinterest上各个引脚的URL。例如:https://www.pinterest.com/pin/146578162860144581/
我想用B列中URL的主图像填充C列中的单元格。
目前,我必须手动执行此操作,方法是单击B列中的URL,复制图像URL,然后将图像插入到C列中的单元格中。
有没有办法让这一切自动化呢?
发布于 2020-02-19 11:43:28
解决方案
是的,你可以使用工作表的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+'")');
}
}
结果
解释
要在工作表的网站中插入图像,您需要图像url。这是这个问题中最棘手的部分。Pinterest并没有提供一种通过直接获取pin url来获取该图像url的好方法,因为该请求将返回HTML数据而不是json。要实现这一点,您需要向此url https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=PINIDNUMBER
发出fetch请求。你可以在this Stack Overflow question上找到更多关于这方面的信息,功劳是@SambhavSharma。
当你跟随这个url进行抓取时,你会得到图钉的json,你可以从中检索你想要的图片url (除了关于这个图钉的许多其他数据)。使用它,您只需将其插入到下一列中。
我希望这对你有所帮助,如果你还需要什么,或者你不明白什么,请告诉我。
https://stackoverflow.com/questions/60286003
复制相似问题