如何使用Python从雅虎财经中提取实时价格、价格变化和变化百分比?

问题描述 投票:0回答:2

我需要使用此页面上可以找到的数据来抓取 2000 多个代码的数据:https://finance.yahoo.com/quote/AAPL。我能够获取交易量、出价等的代码,但一直在努力获取股票代码、实时价格、变化百分比和变化。

我检查了 html 结构,目前有这段代码,但我最终没有得到我需要的数据(一切都是 NA)。我不完全理解如何分析 html 结构以及如何挑选正确的部分来获得我需要的内容。我真的很感激一些见解。谢谢!

import requests
from bs4 import BeautifulSoup

# Define the URL
`url = 'https://finance.yahoo.com/quote/AAPL'

# Send a GET request to the URL
response = requests.get(url)

# Parse the HTML content
soup = BeautifulSoup(response.content, 'html.parser')

# Extract the price
price_element = soup.find('div', {'data-field': 'regularMarketPrice'})
price = price_element.text.strip() if price_element else 'N/A'

# Extract the live price
live_price_element = soup.find('fin-streamer', {'data-testid': 'qsp-price'})
live_price = live_price_element.text.strip() if live_price_element else 'N/A'

# Extract the change
change_element = soup.find('fin-streamer', {'data-field': 'regularMarketChange'})
change = change_element.text.strip() if change_element else 'N/A'

# Extract the change percent
percent_element = soup.find('fin-streamer', {'data-field': 'regularMarketChangePercent'})
percent_change = percent_element.text.strip() if percent_element else 'N/A'

# Print the extracted data
print('Price:', price)
print('Live Price:', live_price)
print('Change:', change)
print('Percent Change:', percent_change)
python web-scraping yahoo-finance
2个回答
1
投票

怎么样

import yfinance as yf
aapl = yf.Ticker("AAPL")

0
投票

我创建了 2 个脚本来抓取雅虎财经,但在抓取“绩效”页面(例如“月份百分比”)时找不到正确的标签 有人可以帮忙吗?

© www.soinside.com 2019 - 2024. All rights reserved.