【问题标题】:How to use IMPORTXML on Google Spreadsheet to get premarket value for a stock?如何在 Google 电子表格上使用 IMPORTXML 获取股票的上市前价值?
【发布时间】:2020-06-19 12:23:44
【问题描述】:

我正在尝试获取this 股票的当前上市前价格。这是我正在尝试的公式:

=IMPORTXML("https://www.marketwatch.com/investing/stock/mtsl", "//bg-quote[@session='pre']")

我没有得到价值:

有什么想法吗?

【问题讨论】:

    标签: javascript google-apps-script google-sheets google-sheets-importxml


    【解决方案1】:

    我了解到您想在表格中查看 MarketWatch 的股票价格。不幸的是,您不能使用=IMPORTXML("https://www.marketwatch.com/investing/stock/oln", "/"),因为您会收到这样的 JavaScript 响应:

    (function(window) {
      try {
        if (typeof sessionStorage !== 'undefined') {
          sessionStorage.setItem('distil_referrer', document.referrer);
        }
      } catch (e) {}
    })(window);
    #d__fFH {
      position: absolute;top: -5000 px;left: -5000 px
    }
    #d__fF {
      font - family: serif;
      font - size: 200 px;
      visibility: hidden
    }
    #fwqssyztxufxfzwwduebdqwxedwrzazqaaavux {
      display: none!important
    }
    

    出现此行为的原因是 IMPORTXML 期望 URL 中包含 XML 页面,并且由于此 URL 未处理 XML 兼容文件,因此它将尽最大努力返回页面加载。在这种情况下,服务器会优雅地引发错误,因为它需要定义的会话存储来确定浏览器 cookie 协议。为了防止这种不兼容,您可以使用Apps Script 代码来获取股票价格,如下所示:

    function listingPrice() {
      return UrlFetchApp.fetch("https://www.marketwatch.com/investing/stock/mtsl")
        .getContentText().match(/(<meta name="price" content=")(.*)(?=")/)[2];
    }
    

    在该示例中,我使用UrlFetchApp.fetch() 获取页面,使用HTTPResponse.getContentText() 读取其内容,并使用String.match() 使用regexp 获取价格。为了防止盘中值,您可以开发如下示例的条件:

    function listingPrice() {
      var stock = UrlFetchApp.fetch(
        "https://www.marketwatch.com/investing/stock/mtsl").getContentText();
      if (stock.match(/(<div class="status">)(.*)(?=<\/div>)/)[2] == "Premarket") {
        return stock.match(/(<meta name="price" content=")(.*)(?=">)/)[2];
      } else {
        return "NASDAQ:MTSL is trading at this time.";
      }
    }
    

    然后您可以将价格保存在工作表上:

    function refreshSheet() {
      SpreadsheetApp.getActiveSheet().getRange(1, 1).setValue(listingPrice());
    }
    

    SpreadsheetApp.getActiveSheet() 将打开活动表以使用Sheet.getRange() 选择A1 范围并使用Range.setValue() 写入价格。请不要犹豫,问我更多问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多