HTTPError:HTTP错误400:错误请求

时间:2015-02-09 19:48:50

标签: python

我已经写了这个python脚本来获取谷歌财经的股票报价。然而,如果我输入谷歌没有的股票代码,那么脚本就像写了一样,我得到了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']
 ))

1 个答案:

答案 0 :(得分:2)

只需将您的代码放在try - except块中,然后捕获错误:

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
相关问题