gpt4 book ai didi

python - HTTP错误 : HTTP Error 400: Bad Request

转载 作者:太空宇宙 更新时间:2023-11-04 03:37:15 27 4
gpt4 key购买 nike

我编写了这个 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

关于python - HTTP错误 : HTTP Error 400: Bad Request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28418037/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com