我了解到您想在表格中查看 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() 写入价格。请不要犹豫,问我更多问题。