从雅虎财经看股票市场价值

2024-03-29 04:42:56 发布

您现在位置:Python中文网/ 问答频道 /正文

import urllib.request, urllib.error

m = 0 
web ='x'  # This reads the stock value for "United States Steel Corp."
t =str(web)
try: f = urllib.request.urlopen('http://finance.yahoo.com/q?s='+ t +'')
except ValueError:
    print(str('Error'))
    m = 1
    pass

if m == 0:
    urlText = f.read().decode('utf-8')

    if urlText.find('<span id="yfs_l84_'+ t +'">'):
        cat = urlText[urlText.find('<span id="yfs_l84_'+ t +'">'):urlText.find('<span id="yfs_l84_'+ t +'">')+30]
        dog = cat.strip('</span></span>')
        dog = cat.strip('<span id="yfs_l84_'+ t +'">')
        print('United States Steel Corp. = ', dog)
    else:print("---> Couldn't read URL text")

这个程序正在读取特定公司缩写的股票价值。在我的例子中,第3行是web ='x'

我想要实现的是,如果我在指定的web变量中输入更多的缩写,那么我应该能够显示所有输入的缩写的股票价值。我的意思是:web = 'x', 'y', 'z'。在

我不知道如何在我的程序中实现这一点。我相信我需要创建一个数组,然后使用for循环进行循环。但是,我不确定。在

谢谢!!在


Tags: webidforrequestfindurllibcatunited
2条回答

通过使用+连接符号(例如AAPL+GOOG+MSFT),可以通过YFinance API请求报价。要加入这样的符号列表,'+'.join(symbols)。然后需要附加&f=...。我已经用&f=a得到了要价。在

import urllib

symbols = ['MSFT', 'AAPL', 'GOOG']

# To request ask (delayed) for all symbols.
url_req = ("http://finance.yahoo.com/d/quotes.csv?s={symbols}&f=a"
           .format(symbols="+".join(symbols)))

prices = urllib.request.urlopen(url_req).read().decode().split('\n')

# Use dictionary comprehension together with zip to get dict of values.
ask_quotes = {symbol: quote for symbol, quote in zip(symbols, prices)}

>>> url_req
'http://finance.yahoo.com/d/quotes.csv?s=MSFT+AAPL+GOOG&f=a'

>>> ask_quotes
{'AAPL': '114.60', 'GOOG': '614.920', 'MSFT': '43.93'}

Python中的数组称为列表!你可以这样做:

web = ['x','y','z']

为了循环使用它们,你可以像:

^{pr2}$

这个链接也可以帮助你学习Python:Python Track in CodeAcademy

编辑:OP正在找字典。在

companies = {
        'Company A' : 15,
        'Company B' : 6 
        }

在字典中,可以通过元素的索引访问元素:companies['Company A']将返回其值6

相关问题 更多 >