我编写了这个 python 脚本来从 google finance 获取股票报价。该脚本按照编写的方式工作,但是,如果我输入谷歌没有的股票代码,我会收到 HTTPError。我是 python 编程的初学者,不确定如何处理脚本中的 HTTPError。我查看了其他提出的问题,但没有一个适用或能够帮助我完成我的任务。
import json
import urllib2
url = 'https://finance.google.com/finance/info?client=ig&q=%s' % symbol
lines = urllib2.urlopen(url).read().splitlines()
j = json.loads(''.join([x for x in lines if x not in ('// [', ']')]))
bot.say('%s %s: (%s) %s' % (
j['t'],
j['l'],
j['c'],
j['lt']
))
请您参考如下方法:
只需将您的代码放在 try-except block 中并捕获抛出的错误:
import json
import urllib2
url = 'https://finance.google.com/finance/info?client=ig&q=%s' % symbol
try:
lines = urllib2.urlopen(url).read().splitlines()
j = json.loads(''.join([x for x in lines if x not in ('// [', ']')]))
bot.say('%s %s: (%s) %s' % (
j['t'],
j['l'],
j['c'],
j['lt']
))
except urllib2.HTTPError:
pass #or do your custom error message handling here
