在Google Apps脚本中触发importHTML

时间:2017-02-11 02:21:10

标签: google-apps-script

我想知道是否可以编写一个Google Apps脚本,该脚本会在Google电子表格中触发每日importhtml。例如,我们假设我想每天下午1点导入下表的更新。

=IMPORTHTML("https://en.wikipedia.org/wiki/Lubbock,_Texas","table",5)

即使计算机处于脱机状态,我也需要自动检查表更新。 谢谢

1 个答案:

答案 0 :(得分:1)

是的,可以编写一个脚本来每天制作一份表格副本。 简而言之,您必须复制导入的表并将其粘贴到新的工作表中。每次打开/访问电子表格时,ImportHTML都会更新。因此,只有存储表的方法是复制并将其粘贴到新工作表中。

以下是执行此操作的代码:

function getImportData()
{
 var ss = SpreadsheetApp.getActive()
var sheet =ss.getSheetByName("ImportSheet")

if (sheet == null)
{  
sheet = ss.insertSheet("ImportSheet")
sheet.getRange(1,1).setValue( "=IMPORTHTML(\"https://en.wikipedia.org/wiki/Lubbock,_Texas\",\"table\",5)")
}
var dataRange = sheet.getDataRange()
//waitforLoading waits for the function importHTML to finish loading the table, only a problem if table takes a while to load
//for more discussion on this visit : http://stackoverflow.com/questions/12711072/how-to-pause-app-scripts-until-spreadsheet-finishes-calculation
var wait = waitForLoading(dataRange,sheet, 10)
var logSheet = ss.getSheetByName("ImportLogSheet")
 if (logSheet == null)
  {  
    logSheet = ss.insertSheet("ImportLogSheet")
  }
  var timeStampRow = []
  timeStampRow[0] = new Date()
if(wait)
{
  logSheet.appendRow(timeStampRow)
  var lastRow = logSheet.getLastRow() + 1
  var destinationRange = logSheet.getRange(lastRow,1)
  dataRange.copyTo(destinationRange, {contentsOnly:true})  

}
  else {
    timeStampRow[1] = "Scripted timeout waiting for the table to Load " 
    logSheet.appendRow(timeStampRow)
  }
}

function waitForLoading(dataRange, sheet, maxWaitTimeInSec)
{
 // This function is only required if it takes a while for the importHTML to load your data!
 // if not you can skip this function

  // Function looks to see if the value of the  
for(i = 0; i< maxWaitTimeInSec ; i++)
{
  var value = dataRange.getCell(1,1).getValue()
  if(value.search("Loading") !== -1) {
    Utilities.sleep(1000);
    dataRange = sheet.getDataRange()
  } else {
   return true
  }

}
  return false

}

修改:忘了提及设置触发器。您可以使用时间驱动的触发器设置要触发的任何功能。有关如何设置的详细信息,请参见:https://developers.google.com/apps-script/guides/triggers/installable#managing_triggers_manually