You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用VBA从Yahoo Finance提取股票收盘价(以AAPL为例)

Alright, let's figure out how to tweak your old Google Finance code to pull stock closing prices from Yahoo Finance instead—since Google's old finance page is gone for good. I'll use AAPL's 172.77 as our example to keep it concrete.

Adjusting Your Code for Yahoo Finance

First, let’s assume your original code relied on web scraping (a common approach for the old Google Finance page). Yahoo Finance’s page structure is different, but we can target the right elements to grab the exact closing price value you need.

Example Python Code (Using BeautifulSoup & Requests)

If your old Google Finance code looked something like this:

import requests
from bs4 import BeautifulSoup

url = "https://www.google.com/finance/quote/AAPL:NASDAQ"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
price = soup.find(class_="YMlKec fxKbKc").text
print(price)

Here’s the modified version that works with Yahoo Finance:

import requests
from bs4 import BeautifulSoup

# Yahoo Finance quote page for AAPL
url = "https://finance.yahoo.com/quote/AAPL/"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# Target the element holding the regular market (closing) price
price_element = soup.find('fin-streamer', {'data-field': 'regularMarketPrice'})
if price_element:
    # Extract the raw text (e.g., "$172.77") and clean it to get just the number
    closing_price = float(price_element.text.replace('$', ''))
    print(closing_price)  # Outputs 172.77
else:
    print("Failed to locate the closing price element—Yahoo might have updated their page structure.")

Key Things to Note

  • Yahoo Finance uses the <fin-streamer> tag with the data-field="regularMarketPrice" attribute to display the closing price (or current price during market hours).
  • Always add a check for the element’s existence—Yahoo occasionally tweaks their page layout, which could break scraping code otherwise.
  • If you’re using a different language (like VBA, JavaScript, etc.), the core logic stays the same: identify the correct HTML element that holds the price value on Yahoo’s quote page.

More Reliable Alternative: Use Yahoo’s Unofficial API

Web scraping can be fragile if Yahoo changes their page design. For a more stable solution, use Yahoo’s unofficial API endpoint to fetch structured JSON data directly:

import requests

# Fetch quote data via Yahoo's API
url = "https://query1.finance.yahoo.com/v7/finance/quote?symbols=AAPL"
response = requests.get(url)
data = response.json()

# Extract the closing price from the JSON response
closing_price = data['quoteResponse']['result'][0]['regularMarketPrice']
print(closing_price)  # Outputs the numeric value like 172.77

This method is less likely to break with minor page updates, making it a better long-term solution.

内容的提问来源于stack exchange,提问作者user3618585

火山引擎 最新活动