我目前正在从雅虎财经中提取数据。使用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('  ')[0]
if len(gw) < 14:
gw = gw
else:
gw = '-'
return gw
print(eachStock, bsYhooStats(bsUrl))
except IndexError:
pass
yhooKeyStats()
答案 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