我正在尝试编写一个代码,以便获得 Winamax 上所有足球比赛的赔率。 我尝试了 Youtube 上的一个视频来解释如何操作,但是有一个问题 - 视频中没有出现这个问题。
当我用它的键请求一个值时,它不起作用。它显示 KeyError 错误。 同时,密钥实际上存在,如果我尝试使用同一字典上的“matchId”,它就可以工作。
如果你能帮助我,谢谢!
朱尔斯
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())
错误:
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'
大多数游戏都有
mainBetId
键,但有些(大约四分之一)没有。
您的代码需要在尝试访问该密钥之前检查该密钥是否存在。