【问题标题】:Python - BeautifulSoup: Pull stock data from MorningstarPython - BeautifulSoup:从晨星提取股票数据
【发布时间】:2022-01-22 17:47:38
【问题描述】:

我正在尝试从 Morning Star 网站提取公司列表的两个数据点并将其保存到文本文件中,但我不确定如何处理此任务。以下是我的代码:

from bs4 import BeautifulSoup as BS

thislist = ["AAPL","FB","TSLA","DIS"] 
for symbol in thislist:
    print ('Getting data for ' + symbol + '...\n')

# extract from this website
url="https://www.morningstar.com/stocks/xnas/" + symbol + "/quote"
        
soup = BS(url)
        
# Find the Value of Last Close Price
for text in soup.find_all('div class', name_='Last Close'):
    Last_Close = text.find_all('dp-value price-down')
    print(Last_Close)     
        
# Find the Value of its Market Cap
for text in soup.find_all('div class', name_='Market Cap'):
    Market_Cap = text.find_all('dp-value')
    print(Market_Cap)      
        
# Print the table
print(symbol, Last_Close, Market_Cap)
            
# Save the data in a .txt file
df.to_csv(r'c:\data\testing.txt', header=None, index=None, sep=' ', mode='a')

【问题讨论】:

  • 好的,但有什么问题?你必须清楚地说明为什么这不是你想要的How do I ask a good question?。请向我们展示现有的输出或错误消息。
  • 另外,请务必标记 Python 问题python,以便人们更快地看到它们。而这个也是关于web-scraping。 (你可以浏览现有的问答,有很多关于这个的现有问题。)但你仍然需要陈述一个具体的问题。请浏览SO Help 以了解如何表达问题。

标签: python web-scraping beautifulsoup


【解决方案1】:

与使用更接近原始数据源的工具相比,开发用于从网站提取数据的抓取工具对实时市场状况的反应要慢一些。有多种库存包非常有用。以下是使用 Pandas DataReader、yfinance 的一些有用链接:

https://www.mssqltips.com/sqlservertip/6826/techniques-for-collecting-stock-data-with-python/ https://towardsdatascience.com/how-to-get-stock-data-using-python-c0de1df17e75

就我个人而言,我更喜欢使用 Pandas,因为它对我来说更可靠,而且我的所有数据通常最终都会存储在 Pandas 的数据框中。 DataReader 也可以直接从 Morningstar 中提取:https://pandas-datareader.readthedocs.io/en/v0.6.0/readers/morningstar.html

此外,如果您有兴趣开发深入的交易系统,Quandl 非常适合分析历史数据。 https://analyzingalpha.com/nasdaq-data-link-quandl-python-api

【讨论】:

  • 谢谢我先生!我很快就会阅读并测试 Pandas :)
【解决方案2】:

首先,这段代码将为您提供所需的信息:

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
import time

symbols = ["AAPL", "FB", "TSLA", "DIS"]


def download_data(symbol):
    url = f'https://www.morningstar.com/stocks/xnas/{symbol}/quote'
    s = Service(ChromeDriverManager().install())
    op = webdriver.ChromeOptions()
    op.headless = True
    driver = webdriver.Chrome(service=s, options=op)
    driver.get(url)

    # symbol, Last_Close, Market_Cap
    time.sleep(2)


    last_close = driver.find_element(by=By.XPATH,
                                         value='//*[@id="__layout"]/div/div[2]/div[3]/main/div[2]/div/div/div[1]/div[1]/div/sal-components/section/div/div/div/sal-components-quote/div/div/div/div/div/div[2]/ul/li[1]/div/div[2]')
    market_cap = driver.find_element(by=By.XPATH,
                                          value='//*[@id="__layout"]/div/div[2]/div[3]/main/div[2]/div/div/div[1]/div[1]/div/sal-components/section/div/div/div/sal-components-quote/div/div/div/div/div/div[2]/ul/li[7]/div/div[2]')
    return symbol, last_close.text, market_cap.text


for symbol in symbols:
    print(download_data(symbol))

输出如下所示:

('AAPL', '164.51', '2.6529 Tril')
('FB', '316.56', '843.3460 Bil')
('TSLA', '996.27', '947.9256 Bil')

迪士尼的页面实际上并不存在,因此您可能需要考虑检查网址。

您可以根据需要将其保存在数据框中以导出到 csv。我建议使用 Selenium 而不是 Beautiful Soup。您消除了尝试查找使用 Javascript 动态呈现的信息的麻烦……有时,Beautiful Soup 会遇到麻烦。 Selenium 的行为就像您访问网页时一样。

同样在您的代码中,您尝试soup = BS(url)。我相信你需要在 python 中使用requests 库发出 HTTP 请求,但我有一段时间没有使用BS

【讨论】:

  • 非常感谢乔!我试图在 Spyder (Python 3.9) 上运行它,但它显示了一条错误消息。我将 chromedriver.exe 下载到我的计算机(Windows 10),但我不知道为什么它不起作用...... :( 在过去的几个小时里试图研究谷歌但仍然没有运气......你能帮我吗?消息:从 webdriver_manager.chrome 导入 ChromeDriverManager ModuleNotFoundError:没有名为“webdriver_manager”的模块
  • 您需要打开一个终端并输入 pip install webdriver-manager。点击 windows 键并输入 cmd 并输入。这将打开一个黑色终端窗口,然后键入该行。
  • 我在答案中包含的代码会为您下载 chrome 驱动程序和所有内容。您只需要 selenium 模块和 webdriver-manager 模块。如果你没有 selenium,你可以在终端 pip install selenium 中输入。 Pip 是一个包管理器...帮助您从 PyPI 下载模块
  • @Obe 这最终解决了您的问题吗?如果确实如此,我将不胜感激您将其标记为正确,否则我可以尝试进一步提供帮助!
  • 再次感谢乔!是的,您的代码解决了我的问题。
猜你喜欢
  • 2019-01-07
  • 1970-01-01
  • 1970-01-01
  • 2019-06-27
  • 2020-07-08
  • 2016-06-10
  • 1970-01-01
  • 2020-05-11
  • 1970-01-01
相关资源
最近更新 更多