Google Script调用Tesouro Direto API返回403的绕过方案求助
解决方案:绕过Tesouro Direto API的Cloudflare拦截
方案1:模拟浏览器请求头
Cloudflare的拦截逻辑通常会校验请求的User-Agent等标识字段,Google Script的UrlFetchApp默认请求头会被识别为非浏览器流量,添加浏览器常用请求头可尝试绕过拦截。
修改后的代码:
function TESOURODIRETO() { let srcURL = "https://www.tesourodireto.com.br/json/br/com/b3/tesourodireto/service/api/treasurybondsinfo.json"; let options = { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", "Accept-Language": "pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3", "Referer": "https://www.tesourodireto.com.br/" } }; try { let jsondata = UrlFetchApp.fetch(srcURL, options); let data = JSON.parse(jsondata.getContentText()); console.log(data); return data; } catch (e) { console.log("请求错误:" + e.message); return null; } }
方案2:用Google Cloud Functions做中转代理
若方案1无效,可搭建轻量中转代理,利用Google Cloud Functions的动态IP池绕过固定IP拦截(Cloud Functions的出口IP不会被长期拉黑)。
操作步骤:
- 登录Google Cloud控制台,创建新的Cloud Function
- 触发器选择HTTP,允许未认证访问(按需配置权限)
- 选择Node.js环境,编写以下代理代码:
exports.tesouroProxy = (req, res) => { const fetch = require('node-fetch'); const targetUrl = "https://www.tesourodireto.com.br/json/br/com/b3/tesourodireto/service/api/treasurybondsinfo.json"; fetch(targetUrl, { headers: { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36", "Referer": "https://www.tesourodireto.com.br/" } }) .then(response => response.json()) .then(data => res.json(data)) .catch(err => res.status(500).send(err.message)); };
- 部署后复制函数的HTTP触发URL,在Google Script中调用该代理:
function TESOURODIRETO() { let proxyURL = "你的Cloud Functions触发URL"; try { let jsondata = UrlFetchApp.fetch(proxyURL); let data = JSON.parse(jsondata.getContentText()); console.log(data); return data; } catch (e) { console.log("请求错误:" + e.message); return null; } }
方案3:通过Google Sheets中转数据
若不想搭建代理,可借助Google Sheets的IMPORTDATA函数先获取API数据,再从表格中读取解析:
- 在Google Sheets的任意单元格输入:
=IMPORTDATA("https://www.tesourodireto.com.br/json/br/com/b3/tesourodireto/service/api/treasurybondsinfo.json")
- 数据加载完成后,在Google Script中读取表格内容:
function TESOURODIRETO() { let sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("你的工作表名称"); let jsonText = sheet.getRange("A1").getValue(); // 假设数据起始于A1单元格 try { let data = JSON.parse(jsonText); console.log(data); return data; } catch (e) { console.log("解析错误:" + e.message); return null; } }
注:若IMPORTDATA也被拦截,可改用Sheets脚本的UrlFetchApp模拟浏览器请求头获取数据并写入表格。
内容的提问来源于stack exchange,提问作者Rafael Guimaraes de Paula
相关产品推荐
相关产品推荐

