优化抓取Instagram帖子数据的谷歌脚本

时间:2018-03-07 21:39:32

标签: google-apps-script google-sheets instagram

在过去几天/几周内,我一直致力于将Google数据导入电子表格的Google脚本。到目前为止,我已成功设法抓住追随者,跟踪数据,参与率和帖子数量以及每日更改。

我现在正在努力寻找一种方法,允许我逐个帖子级别获取数据并每天更新数据。但是因为我真的是编程新手。我以非常低效的方式进行此操作,并且我不知道如何更新现有行。

这是我到目前为止所做的:

// Get Date field filled
function insertPostData(sheetName, instagramAccountName) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(sheetName); 
  sheet.appendRow([Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), Post1Comment(instagramAccountName)]); 
  sheet.appendRow([Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd"), Post2Comment(instagramAccountName)]); 
  Utilities.sleep(200);
}; 



//Write post1 comments to Sheet
function Post1Comment(username) { 
  var url = "https://www.instagram.com/" + username + "/?__a=1", totalCount = 0;
  var response = UrlFetchApp.fetch(url).getContentText();
    for(var i = 0; i < 12; i++) {
      totalCount += parseInt(JSON.parse(response).user.media.nodes[i].comments.count);
     return totalCount;
}}

//Write post2 comments to Sheet
function Post2Comment(username) { 
  var url = "https://www.instagram.com/" + username + "/?__a=1", totalCount = 0;
  var response = UrlFetchApp.fetch(url).getContentText();
    for(var i = 1; i < 12; i++) {
      totalCount += parseInt(JSON.parse(response).user.media.nodes[i].comments.count);
     return totalCount;
}}

这个我需要12个帖子(你可以从https://www.instagram.com/username/?__a=1网址自由抓取。想想我想抓住多个对象的事实(发布日期,喜欢,评论,媒体ID,。 。)从每个帖子做这种方式会非常低效......

任何人都可以帮助找到正确的方向来提高效率吗?

1 个答案:

答案 0 :(得分:1)

如何使用UrlFetchApp.fetchAll()?最近,添加了这种方法。此方法可以获取多个请求。

fetchAll(),可以使用带有请求的数组执行请求。来自fetchAll()的响应是一个数组。并且响应数组中的索引对应于所请求数组的索引。我认为这可以用于你的情况。

当您使用此方法时,修改后的脚本如下所示。

流程:

  • 创建请求数组。
  • 使用创建的请求获取。
  • 转换检索到的数据以导入到电子表格。
  • 导入转换后的数据。

修改后的脚本:

function insertPostData(sheetName) {
  var userNames = [
    "instagramAccountName1",
    "instagramAccountName2",
    "instagramAccountName3",
    ,
    ,
  ]; // Please input instagramAccountNames here.

  var requests = userNames.map(function(e){return {"url": "https://www.instagram.com/" + e + "/?__a=1", "method": "get"}});
  var response = UrlFetchApp.fetchAll(requests);
  var date = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd");
  var totalCounts = [];
  for (var j in response) {
    var totalCount = 0;
    for(var i = 1; i < 12; i++) {
      totalCount += parseInt(JSON.parse(response[j]).user.media.nodes[i].comments.count);
    }
    totalCounts.push([date, totalCount]);
  }
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName(sheetName);
  sheet.getRange(sheet.getLastRow() + 1, 1, totalCounts.length, totalCounts[0].length).setValues(totalCounts);
}

参考:

如果我误解了你的问题,我很抱歉。如果这不起作用,请告诉我。我想修改。