Home > Net >  Python loop code with try: & except: pass
Python loop code with try: & except: pass

Time:11-27

When scraping list of json files, sometimes, file are missing and can't be downloaded. On my python script, when that case occurs, the script display an error

json.decoder.JSONDecodeError : Expecting value: linke 1 column 1 (char 0)

How can I ask to the script to continue the loop if error ? I tried to put and try: except, but without success (IndentationError)

This is the code :

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)

CodePudding user response:

put the try and except blocks this way-

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
  • Related