-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathYAHOOFINANCE.gs
68 lines (60 loc) · 2.4 KB
/
YAHOOFINANCE.gs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/**
* 從 Yahoo Finance 抓取指定股票的數據
* @param {string} symbol - 股票代號,例如 "00864B.TWO"
* @param {string} attribute - 要抓取的屬性 ("price" 或 "changepct")
* @customfunction
*/
function YAHOOFINANCE(symbol, attribute) {
// 驗證輸入
if (!symbol || !attribute) {
return "請提供股票代號和屬性";
}
var url = "https://finance.yahoo.com/quote/" + symbol + "/";
var options = {
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
},
"muteHttpExceptions": true
};
try {
// 抓取網頁內容
var response = UrlFetchApp.fetch(url, options);
var html = response.getContentText();
if (attribute.toLowerCase() === "price") {
// 使用更精確的正則表達式匹配價格
var pricePattern = /<fin-streamer[^>]*data-symbol="[^"]*"[^>]*data-field="regularMarketPrice"[^>]*value="([^"]*)"/i;
var match = html.match(pricePattern);
if (match && match[1]) {
return parseFloat(match[1]); // 直接使用value屬性中的數值
} else {
return "無法抓取價格";
}
} else if (attribute.toLowerCase() === "changepct") {
// 精準解析百分比變化(匹配帶括號的百分比)
var pctMatch = html.match(/data-testid="qsp-price-change-percent"[^>]*>.*?\(([+-]?\d+\.\d+)%\)/is);
if (pctMatch) {
return parseFloat(pctMatch[1]);
}
// 備用方案:直接匹配百分比數值
var altMatch = html.match(/data-testid="qsp-price-change-percent"[^>]*>.*?([+-]?\d+\.\d+)%?/is);
return altMatch ? parseFloat(altMatch[1]) : "無法抓取漲跌幅";
} else {
return "無效屬性,請使用 'price' 或 'changepct'";
}
} catch(e) {
return "抓取失敗,請檢查網路連線";
}
}
// 可選:手動寫入指定股票數據到 A1 和 B1
function writeDataToSheet() {
var sheet = SpreadsheetApp.getActiveSheet();
var symbol = "00864B.TWO"; // 可修改為其他股票代號
var price = YAHOOFINANCE(symbol, "price");
var changePct = YAHOOFINANCE(symbol, "changepct");
if (price !== "無法抓取價格" && price !== "無效屬性") {
sheet.getRange("A1").setValue(price);
}
if (changePct !== "無法抓取漲跌幅" && changePct !== "無效屬性") {
sheet.getRange("B1").setValue(changePct);
}
}