簡體   English   中英

如何在谷歌電子表格上使用 IMPORTXML 來獲取股票的上市前價值?

[英]How to use IMPORTXML on Google Spreadsheet to get premarket value for a stock?

我正在嘗試獲取這只股票當前的上市前價格。 這是我正在嘗試的公式:

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

我沒有得到價值:

結果

有任何想法嗎?

我了解到您想在 Sheets 中查看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 兼容的最佳頁面加載工作在這種情況下,服務器會優雅地引發錯誤,因為它需要定義的 session 存儲來確定瀏覽器 cookie 協議。 為了防止這種不兼容,您可以使用Apps 腳本代碼來獲取股票價格,如下所示:

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 范圍 select 的活動表,並使用Range.setValue() Sheet.getRange()寫入價格。 請不要猶豫再問我更多問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM