urllib.request.urlopen(stock_price_url).read()。decode()

时间:2016-12-20 19:34:30

标签: python csv url

我正在尝试youtube教程中的以下代码: https://www.youtube.com/watch?v=83-_3x2AjXI&t=3s

不知何故,代码卡在了这一行:

source_code = urllib.request.urlopen(stock_price_url).read().decode()

没有任何反应,我也没有收到任何错误消息。

我还在浏览器上测试了网址:

http://chartapi.finance.yahoo.com/instrument/1.0/TSLA/chartdata;type=quote;range=10y/csv

它工作正常。

我正在使用MacOS和python 3.5.2。有什么建议吗?我安装python可能有问题吗?

import matplotlib.pyplot as plt
import numpy as np
import urllib
import matplotlib.dates as mdates

def bytespdate2num(fmt, encoding='utf-8'):
    strconverter = mdates.strpdate2num(fmt)
    def bytesconverter(b):
        s = b.decode(encoding)
        return strconverter(s)
    return bytesconverter


def graph_data(stock):

    print("hello 10\n")

    stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=10y/csv'
    print("hello 11\n")
    source_code = urllib.request.urlopen(stock_price_url).read().decode()

    print("hello 12\n")
    stock_data = []
    split_source = source_code.split('\n')
    print("hello 13\n")

    for line in split_source:
        split_line = line.split(',')
        if len(split_line) == 6:
            if 'values' not in line and 'labels' not in line:
                stock_data.append(line)

    date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
                                                      delimiter=',',
                                                      unpack=True,
                                                      # %Y = full year. 2015
                                                      # %y = partial year 15
                                                      # %m = number month
                                                      # %d = number day
                                                      # %H = hours
                                                      # %M = minutes
                                                      # %S = seconds
                                                      # 12-06-2014
                                                      # %m-%d-%Y
                                                      converters={0: bytespdate2num('%Y%m%d')})

    plt.plot_date(date, closep,'-', label='Price')

    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title('Interesting Graph\nCheck it out')
    plt.legend()
    plt.show()

print("hello 3\n")

graph_data('TSLA')

1 个答案:

答案 0 :(得分:0)

我认为您可以为urlopen添加超时

source_code = urllib.request.urlopen(stock_price_url, timeout=5).read().decode()

因此,如果页面的响应时间超过5分钟,则该过程将抛出错误。