首页 > 解决方案 > 使用谷歌金融抓取实时股票价格

问题描述

我最近开始学习 python,我的第一个项目是使用 beautifulsoup 从 Google Finance 获取实时股票价格。基本上我正在寻找股票并设置价格警报。

这是我的代码的样子。

import requests
import time
import tkinter
from bs4 import BeautifulSoup

def st_Price(symbol):
    baseurl = 'http://google.com/finance/quote/'
    URL = baseurl + symbol + ":NSE?hl=en&gl=in"
    
    page = requests.get(URL)
    
    soup = BeautifulSoup(page.content, 'html.parser')
    
    results = soup.find(class_="YMlKec fxKbKc")

    result = results.__str__()
    #print(result)

    res = result.split("₹&quot;)[1].split("<")[0]

    res_flt = float(res.replace(",",""))
      
    return res_flt
        
def main():
    
    sym = input("Enter Stock Symbol : ")
    price = input("Enter desired price : ")
    
    
    x = st_Price(sym)
    
    while x < float(price):
        print(x)
        t1 = time.perf_counter()
        x = st_Price(sym)
        t2 = time.perf_counter()
        print("Internal refresh time is {}".format(t2-t1))
    else:
        print("The Stock {} achieved price greater than {}".format(sym,x))
        root = tkinter.Tk()
        root.geometry("150x150")
        tkinter.messagebox.showinfo(title="Price Alert",message="Stock Price {} greater Than {}".format(x,price))
        root.destroy()
    

if __name__ == "__main__":
    main()

我正在页面 HTML 中查找以下类:

股票的 HTML 元素

该代码运行良好,但获取信息需要花费太多时间:

Enter Stock Symbol : INFY

Enter desired price : 1578
1574.0
Internal refresh time is 9.915285099999892
1574.0
Internal refresh time is 7.2284357999997155

我对HTML不太熟悉。通过参考在线文档,我能够弄清楚如何抓取必要的部分。

有什么方法可以减少获取数据的时间吗?

标签: pythonhtmlpython-3.xbeautifulsoup

解决方案


推荐阅读