【问题标题】:Google Script with Python example - GET Request - HTML result error带有 Python 示例的 Google 脚本 - GET 请求 - HTML 结果错误
【发布时间】:2021-12-24 10:48:34
【问题描述】:

我正在尝试通过 API GET 请求连接 Google 电子表格以从 snov.io 接收一些信息,但我得到的是 HTML 结果而不是 JSON。以下 Python 代码有效,但 Google Appscript 无效。有什么建议?谢谢你:)

Python 代码 - 工作

params = {
  'access_token': token,
  'domain': site,
  'type': 'all',
  'limit': 100,
  'lastId': 0,
  }
res = requests.get('https://api.snov.io/v2/domain-emails-with-info', params=params)
return json.loads(res.text)

AppScript - 不工作 - 收到 HTML 结果

  'access_token': token,
  'domain': site,
  'type': 'all',
  'limit': 100,
  'lastId': 0,
    }

var url = 'https://api.snov.io/v2/domain-emails-with-info'
var response = UrlFetchApp.fetch(url, {method: "get", payload: params, 'muteHttpExceptions': true}); 
var json = response.getContentText()
console.log(response.getContentText())
obj = JSON.parse(json)
result=obj.emails
return result
}

HTML 结果:(

<html>
    <head>
        <meta charset="UTF-8" />
        <meta name="robots" content="noindex,nofollow" />
        <style>                body { background-color: #fff; color: #222; font: 16px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; margin: 0; }
                .container { margin: 30px; max-width: 600px; }
                h1 { color: #dc3545; font-size: 24px; }</style>
    </head>
    <body>
                        <div class="container">
                    <h1>Whoops, looks like something went wrong.</h1>
                </div>
    </body>
</html>

【问题讨论】:

    标签: python html google-apps-script get google-apps-script-api


    【解决方案1】:

    我相信你的目标如下。

    • 您想将以下 python 脚本转换为 Google Apps 脚本。

        params = {
          'access_token': token,
          'domain': site,
          'type': 'all',
          'limit': 100,
          'lastId': 0,
          }
        res = requests.get('https://api.snov.io/v2/domain-emails-with-info', params=params)
        return json.loads(res.text)
      

    这样的话,下面修改的脚本怎么样?

    修改脚本:

    var params = {
      'access_token': token,
      'domain': site,
      'type': 'all',
      'limit': 100,
      'lastId': 0,
    };
    var url = 'https://api.snov.io/v2/domain-emails-with-info';
    var response = UrlFetchApp.fetch(url + "?" + Object.entries(params).map(([k, v]) => k + "=" + v).join("&"), { method: "get", 'muteHttpExceptions': true });
    
    • params在python的request模块中作为GET方法时,即作为查询参数使用。但是,在 Google Apps Script 的“UrlFetchApp.fetch”方法中,当 params 用于 payload 时,它会自动用作 POST 方法。我认为这可能是您的问题的原因。

    参考:

    【讨论】:

    • 嗨@Tanaike,修改后的脚本就像一个魅力!谢谢你,周末愉快。
    • @SKuan 感谢您的回复。我很高兴你的问题得到了解决。也谢谢你。
    猜你喜欢
    • 1970-01-01
    • 2020-04-01
    • 1970-01-01
    • 2019-12-09
    • 2012-09-29
    • 1970-01-01
    • 2019-08-02
    • 1970-01-01
    • 2017-01-14
    相关资源
    最近更新 更多