使用node.js从其他人的Google表格页面抓取数据?



有人能告诉我如何从非我所有的Google Sheets页面中抓取数据吗?使用API不是一个选项。

我看到了很多关于如何使用Sheets存储web抓取数据的教程,但没有看到关于如何从Sheets页面获取信息的教程

希望我可以使用node.js来完成这项工作。有人知道最好的方法吗?

我相信你的目标如下。

  • 您想要从公开共享的Google电子表格中检索值
  • 您希望使用Node.js来实现这一点
  • trying /edit?usp=sharing yielded /edit#gid=0, and /pubhtml yielded page stating: "We're sorry. This document is not published."中发现,谷歌电子表格是公开共享的,而不是作为网络发布

模式1:

在这种模式中;电子表格.values.get"表中的API与API键一起使用。在运行脚本之前,请检索您的API密钥。参考

示例脚本:

const request = require("request");
const apiKey = "###";  // Please set your API key.
const spreadsheetId = "###";  // Please set the Spreadsheet Id.
request.get(
{
url:
`https://sheets.googleapis.com/v4/spreadsheets/${spreadsheetId}/values/A%3AZ?key=${apiKey}`,
json: true,
},
(err, res, body) => {
if (err) {
console.log(body);
return;
}
console.log(body.values);
}
);
  • 运行上述脚本时,第一个选项卡的单元格A:Z中的值将作为二维数组从公共共享的电子表格中返回。

  • 当您想要检索其他选项卡时,请使用表单API中的spreadsheets.get方法检索表单名称。其终点如下。

    https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}?fields=sheets.properties.title&key={apiKey}
    

模式2:

在此模式中,使用由Google Apps Script创建的Web Apps。

用法:

请按照以下流程操作。

1.创建谷歌应用程序脚本的新项目

Web应用程序的示例脚本是Google应用程序脚本。所以请创建一个谷歌应用程序脚本项目。

如果您想直接创建它,请访问https://script.new/.在这种情况下,如果您没有登录谷歌,则会打开登录屏幕。所以请登录谷歌。这样,谷歌应用程序脚本的脚本编辑器就打开了。

2.准备脚本

请将以下脚本(谷歌应用程序脚本(复制并粘贴到脚本编辑器中。此脚本适用于Web应用程序。

function doGet(e) {
const spreadsheetId = e.parameter.spreadsheetId;
const ss = SpreadsheetApp.openById(spreadsheetId);
const values = ss.getSheets().map(s => ({sheetName: s.getSheetName(), values: s.getDataRange().getValues()}));
return ContentService.createTextOutput(JSON.stringify(values));
}

3.部署Web应用程序

  1. 在脚本编辑器上,通过"发布&quot-&gt"部署为web应用程序">
  2. 选择"我">表示"strong>";将应用程序执行为:">
  3. 选择"任何人,即使是匿名的">表示"strong>";谁可以访问该应用程序:">
  4. 单击";部署";按钮为新";项目版本">
  5. 自动打开对话框";需要授权";。
    1. 点击";查看权限">
    2. 选择自己的帐户
    3. 单击";高级";在";此应用程序未经过验证
    4. 单击";转到###项目名称###(不安全(">
    5. 单击";允许";按钮
  6. 单击";OK">
  7. 复制Web应用程序的URL。就像https://script.google.com/macros/s/###/exec
    • 当您修改谷歌应用程序脚本时,请重新部署为新版本。这样,修改后的脚本就会反映到Web应用程序中。请小心

4.使用Node.js测试Web应用程序

请使用浏览器访问Web应用程序的URL,包括以下查询参数。当你已经登录谷歌时,就会运行Web应用程序的脚本。

const request = require("request");
const spreadsheetId = "###";  // Please set the Spreadsheet Id.
const url = "https://script.google.com/macros/s/###/exec";  // Please set the URL of Web Apps.
request.get(
{
url: `${url}?spreadsheetId=${spreadsheetId}`,
json: true,
},
(err, res, body) => {
if (err) {
console.log(body);
return;
}
console.log(body);
}
);
  • 运行上述脚本时,将返回以下结果。

    [
    sheetName: 'Sheet1',
    values: [ [Array], [Array], [Array],,, ]
    },
    {
    sheetName: 'Sheet2',
    values: [ [Array], [Array], [Array],,, ]
    },
    ,
    ,
    ,
    ]
    

注意:

  • 当您修改Web应用程序的脚本时,请将Web应用程序重新部署为新版本。这样,最新的脚本就会反映到Web应用程序中。请小心
  • 谷歌应用程序脚本是一个简单的示例脚本,用于解释实现目标的方法。因此,请根据您的实际情况进行修改

参考文献:

  • 使用API密钥
  • 方法:spreadsheets.values.get
  • 方法:spreadsheets.get
  • Web应用程序
  • 使用Google应用程序脚本利用Web应用程序

最新更新