pythonpython-requestskeyerrorpython-jsons

Key missing while existant html


I'm trying to make a code in order to get the odds of all the soccer games, on Winamax.

I tried a video on Youtube explaining how, but there's a problem - that didn't occur in the video.

When I ask for a value with its key, it doesn't work. It show the KeyError mistake.

Meanwhile, the Key actually exists, and if I try with 'matchId', that is on the same dictionary, it works.

the source code

If you could help me, thank you !

Jules

import requests
import json

def get_page():
    url= "https://www.winamax.fr/paris-sportifs/sports/1/"
    response = requests.get(url, headers={"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/118.0"})
    html = response.text
    return html

def get_json():
    html = get_page()
    split1 = html.split("var PRELOADED_STATE = ")[1]
    split2= split1.split(";</script>")[0]
    return json.loads(split2)

def get_games():
    games=[]
    json = get_json()
    for game in json['matches']:
        if (json['matches'][game]['sportId']!= 1):
            continue
        
        team1 = json['matches'][game]['competitor1Name']
        
        team2 = json['matches'][game]['competitor2Name']

        bet_id = json['matches'][game]['mainBetId']   
import  winamax

print(winamax.get_games())

The error :

Traceback (most recent call last):
  File "/Users/julespeter/Documents/2. VSC/Winamax/TRJ/main.py", line 4, in <module>
    print(winamax.get_games())
          ^^^^^^^^^^^^^^^^^^^
  File "/Users/julespeter/Documents/2. VSC/Winamax/TRJ/winamax.py", line 31, in get_games
    bet_id = json['matches'][game]['mainBetId']
             ~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
KeyError: 'mainBetId'

Solution

  • Most of the games have a mainBetId key, but some don't.

    The code should check if that key exists before trying to access it.