【问题标题】:Problem getting stocks prices from Yahoo Finance从雅虎财经获取股票价格的问题
【发布时间】:2022-01-22 11:28:46
【问题描述】:

我正在从 yahoo Finance(NVIDIA 股票)进行一些网络抓取,我想知道为什么当我运行我的代码时我总是得到相同的值,但是在我的浏览器中当我刷新页面时我得到不同的值(如它应该是),我该如何解决它?

import requests
from datetime import datetime
import time

def Is_Number(string):
    try:
        int(string)
        return True
    except:
        if(string == '.'):
            return True
        else:
            return False



session = requests.Session()
for i in range(10):

    Response = session.get("https://finance.yahoo.com/quote/NVDA?p=NVDA")

    KeyWord = 'data-pricehint'
    Index = Response.text.find(KeyWord) + 26

    GoOn = True
    CurrentPrice = ""
    while(GoOn == True):

    if ( Is_Number(Response.text[Index])):
        CurrentPrice = CurrentPrice + Response.text[Index]
        Index = Index + 1
    else:
        GoOn = False

    CurrentTime = datetime.now().strftime('%H:%M:%S')

    print("# Price:",CurrentPrice,"at",CurrentTime)

    time.sleep(10)

【问题讨论】:

    标签: python web-scraping python-requests


    【解决方案1】:

    你为什么不试试 yfinance 呢?:

    pip install yfinance

    import yfinance as yf
    import time
    
    
    def get_price() -> float:
        return yf.Ticker("NVDA").info.get("regularMarketPrice")
    
    
    def run():
        for i in range(10):
            print(f"{i}: {get_price()}")
            time.sleep(10)
    
    
    if __name__ == '__main__':
        run()
    

    【讨论】:

    • 真的很有用,谢谢,我想我会使用这个库,但我仍然很好奇为什么我的代码不起作用
    • 你的代码做了奇怪的事情,我不明白你为什么连接输出:CurrentPrice = CurrentPrice + Response.text[Index]。也许您没有按预期调用代码,因此您重用会话而不是创建新会话?
    • 我尝试不使用 'requests.Session()' 但它没有改变,还有其他建议吗?
    • 这是我在当前价格为 289.44 时运行代码时得到的输出:# Price: 277.19 at 20:54:43 # Price: 277.19 at 20:54:54 # Price: 277.19 at 20:55:04 # Price: 277.19 at 20:55:14 # Price: 277.19 at 20:55:24
    • 这是您期望的输出吗?如果是,那么它会告诉我您查看了以字符串表示的 html 中的错误索引,因为当我检查 url 时,我可以在那里看到 277.19 值。
    猜你喜欢
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    • 2015-06-11
    • 2021-07-10
    • 1970-01-01
    相关资源
    最近更新 更多