Python HTTPError:HTTP错误400:请求错误

Python HTTPError:HTTP错误400:请求错误,python,Python,我编写这个python脚本是为了从google finance获取股票报价。但是,如果我输入一个谷歌没有的股票符号,我就会得到HTTPError。我是python编程的初学者,不知道如何处理脚本中的HTTPError。我已经研究过其他问题,但没有一个适用于或能够在我的探索中帮助我 import json import urllib2 url = 'https://finance.google.com/finance/info?client=ig&q=%s' % symbol lines

我编写这个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']
 ))

只需将您的代码放入
块中,并捕获抛出的错误:

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

try:block_of_question();除了urlib2.HTTPError:print“有一个错误”
谢谢你的输入我发现我需要除了urlib2.HTTPError:谢谢