使用 Google Apps Script 中的 UrlFetchApp 获取网页并解决服务器错误码 500

我想使用 Google Apps Script 从 YellowPages.com 获取一些列表数据。在 GAS 中使用 UrlFetchApp.fetch(url)(如下所示),服务器会抛出 500 错误。然而,我可以在 Google 表格中使用 IMPORTXML() 在相同的 URL 上正常工作。

为什么会有这种行为差异?在 Google Apps Script 中,我可以做什么不同的事情来实现与 IMPORTXML() 相同的预期结果?

Google 表格

=IMPORTXML("https://www.yellowpages.com/al/accounting-services", "//div[@class='v-card']//a/@href")

这个行为是预期的。结果是一组链接。

Google Apps Script

Code.gs

const ENDPOINT = 'https://www.yellowpages.com/al/accounting-services';
const main = () => {
  const response = UrlFetchApp.fetch( ENDPOINT, );
  const responseContentText = response.getContentText();
  Logger.log('(line 5) responseContentText\n%s', responseContentText,);
  return responseContentText;
}

这个行为与预期不同。结果是一个 500 错误。

错误信息:

Exception: Request failed for https://www.yellowpages.com returned code 500. Truncated server response: <html>
 <head><title>500 Internal Server Error</title></head>
 <body>
 <center><h1>500 Internal Server Error</h1></center>
 <hr><center>openresty</... (使用 muteHttpExceptions 选项以查看完整响应) (第 16 行,文件"Code")

为什么 UrlFetchApp.fetch(url) 方法会抛出错误,有什么方法可以使其像 IMPORTXML() 一样表现?

点赞