【问题标题】:Python loop code with try: & except: passPython 循环代码与 try: & except: pass
【发布时间】:2021-11-27 04:16:09
【问题描述】:

在抓取 json 文件列表时,有时文件丢失,无法下载。 在我的 python 脚本中,当这种情况发生时,脚本会显示错误

json.decoder.JSONDecodeError:期望值:linke 1 column 1 (char 0)

如果出现错误,我如何要求脚本继续循环? 我试了试:except,但没有成功(IndentationError)

这是代码:

RACE_L = x1["pageProps"]["initialState"]["racecards"]["races"][today2]
for r1 in RACE_L:
    id_race = r1["uuid"]
    link2go = link_append + id_race + '.json'
    n1 = "races"
    n12 = "races"
    n2 = r1["uuid"]
    name1 = n12 + '-' + n2
    name1 = today2 + '_' + name1 + '.json'
    with open(path +'%s' %name1,'w',encoding='utf-8') as f2:
        print('Writing %s into file' %name1)
        r3 = requests.get(link2go, headers=headers)
        sleep(2)
        x3 = r3.json()
        json.dump(x3, f2, indent=4, ensure_ascii=False)

【问题讨论】:

  • 您尝试放置 try 和 except 块的代码在哪里?
  • 就在 RACE_L 中的 r1 下方:

标签: python-3.x loops


【解决方案1】:

以这种方式放置 try 和 except 块-

RACE_L = x1["pageProps"]["initialState"]["racecards"]["races"][today2]
for r1 in RACE_L:
    try:
        id_race = r1["uuid"]
        link2go = link_append + id_race + '.json'
        n1 = "races"
        n12 = "races"
        n2 = r1["uuid"]
        name1 = n12 + '-' + n2
        name1 = today2 + '_' + name1 + '.json'
        with open(path +'%s' %name1,'w',encoding='utf-8') as f2:
            print('Writing %s into file' %name1)
            r3 = requests.get(link2go, headers=headers)
            sleep(2)
            x3 = r3.json()
            json.dump(x3, f2, indent=4, ensure_ascii=False)
    except:
        pass

【讨论】:

    猜你喜欢
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-26
    相关资源
    最近更新 更多