Python 3.4:尝试后继续功能和除外

时间:2015-05-20 08:54:46

标签: python-3.x exception-handling

问题

我目前正在从雅虎财经中提取数据。使用try和except时,该函数在达到错误后停止。如何在except语句之后继续执行该函数以获取索引中股票的剩余数据?

index = sp500


def yhooKeyStats():

try:

    for eachStock in index:
        isUrl = 'http://finance.yahoo.com/q/is?s='+eachStock+'+Income+Statement&annual'
        bsUrl = 'http://finance.yahoo.com/q/bs?s='+eachStock+'+Balance+Sheet&annual'
        cfUrl = 'http://finance.yahoo.com/q/cf?s='+eachStock+'+Cash+Flow&annual'


        def bsYhooStats(url):
            req = urllib.request.Request(url)
            resp = urllib.request.urlopen(req)
            respData = resp.read()
            dRespData = respData.decode('utf-8')

            gw = dRespData.split('Goodwill</td><td align="right">')[1].split('&nbsp;&nbsp')[0]

            if len(gw) < 14:
                gw = gw
            else:
                gw = '-'

            return gw

        print(eachStock, bsYhooStats(bsUrl))

except IndexError:
    pass

yhooKeyStats()

输出

MMM 7,050,000 ABT 10,067,000 ABBV 5,862,000 ACN 2,395,894 ACE - ACT 24,521,500 ADT 3,738,000 AES 1,458,000 AET 10,613,200 AFL -

1 个答案:

答案 0 :(得分:1)

只需将try/except 放入循环中即可。几种可能性之一:

for eachStock in index:
    ...
    try:
        def bsYhooStats(url):
            ...
            return gw if len(gw) < 14 else '-'
        print(eachStock, bsYhooStats(bsUrl))
    except IndexError:
        pass