【EXCEL & GAS】Excelで資産管理しよう!
ログインせずに株価を取得する方法 | GAS×ChatGPT リアルタイム株価取得
ソースコード
// ==========================================
//
// 日本株価取得
//
// ==========================================
function StockPriceParserJP(code) {
// ==========================================
// 入力チェック
// ==========================================
if (!code) {
return "N/A";
}
code = String(code).trim().toUpperCase();
// ==========================================
// Google Finance URL
// ==========================================
const url =
"https://www.google.com/finance/quote/" +
code +
":TYO" ;
// ==========================================
// Google Financeへアクセス
// ==========================================
const response = UrlFetchApp.fetch(url, {
muteHttpExceptions: true,
headers: {
"User-Agent": "Mozilla/5.0"
}
});
// ==========================================
// HTTPエラー
// ==========================================
if (response.getResponseCode() !== 200) {
return "N/A";
}
// HTML取得
const html = response.getContentText();
// ==========================================
// HTML Parserで解析
// ==========================================
const dom = HtmlParser.parse(html);
// ==========================================
// 現在の株価を取得
// ==========================================
const priceElement =
dom.querySelector('.N6SYTe [jsname="Pdsbrc"]');
if (!priceElement) {
return "価格が見つかりません";
}
// 株価文字列
const priceText =
priceElement.textContent.trim();
Logger.log("現在値=" + priceText);
if (!priceText) {
return "価格が見つかりません";
}
// ==========================================
// 通貨記号・カンマを削除
// ==========================================
const numberText =
priceText
.replace("$", "")
.replace("¥", "")
.replace("¥", "")
.replace(",", "")
.trim();
// ==========================================
// 数値に変換
// ==========================================
const price = Number(numberText);
if (isNaN(price)) {
return "N/A";
}
return price;
}


