首页 > 解决方案 > 使用 Python 和 BeautifulSoup 从 Yahoo Finance 抓取股票价格

问题描述

我正在尝试使用 Python 和 BeautifulSoup 从 Yahoo Finance 获取股票价格但是,我无法获取具有特定“data-reactid”属性的标签(参见屏幕截图)。请帮我。

Code:
    def getCurrentPrice(self, stockSymbol):
        #stockSymbol is : MSFT for Microsoft
        
        url = "https://finance.yahoo.com/quote/{}".format(stockSymbol)
        source = requests.get(url).text
        soup = BeautifulSoup(source, 'lxml')

        currentPrice = soup.find('span',attrs={"data-reactid": "52"})

        print("{} : {}".format(stockSymbol, currentPrice))

Output:

MSFT : None

#None because the span tag is not being found.

在此处输入图像描述

标签: pythonweb-scrapingbeautifulsoupyahoo-finance

解决方案


该属性data-reactid本质上是动态的,因此您无法真正找到使用它的 dom 元素。尝试这个:

def getCurrentPrice(self, stockSymbol):
    #stockSymbol is : MSFT for Microsoft

    url = "https://finance.yahoo.com/quote/{}".format(stockSymbol)
    source = requests.get(url).text
    soup = BeautifulSoup(source, 'lxml')

    currentPrice = soup.find('span',attrs={"class": "Trsdu(0.3s)"})

    print("{} : {}".format(stockSymbol, currentPrice.get_text()))

推荐阅读