【问题标题】:Scraping stock price from Yahoo Finance using Python & BeautifulSoup使用 Python 和 BeautifulSoup 从 Yahoo Finance 抓取股票价格
【发布时间】:2020-07-08 09:36:20
【问题描述】:

我正在尝试使用 Python 和 BeautifulSoup 从雅虎财经抓取股票价格。但是,我无法获取具有特定“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.

【问题讨论】:

  • data-reactid 不断变化。当然你会发现它没有被发现。
  • @ManojKumar 谢谢!明白了。

标签: python web-scraping beautifulsoup yahoo-finance


【解决方案1】:

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()))

【讨论】:

    猜你喜欢
    • 2021-12-20
    • 2018-01-02
    • 2020-11-28
    • 2017-01-08
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多