Python脚本无法刷新Reddit JSON获取新Magic Arena兑换码求助
问题分析与解决方案
你的代码核心问题是while循环里没有重新获取Reddit的最新JSON数据——你只在循环前拉取了一次帖子数据,之后循环一直遍历的是最初的旧数据,自然抓不到运行后新发布的帖子。
关键修改点:
- 将请求Reddit JSON的逻辑移到while循环内部,每次循环都重新拉取最新帖子数据
- 新增已处理帖子ID的记录,避免重复处理同一个兑换码(不然每次循环都会重复提交旧代码)
- 去掉冗余的
json.dumps+json.loads操作,直接使用response.json()返回的字典 - 输入兑换码前清空输入框,防止多次输入叠加
修改后的完整代码
from selenium import webdriver from selenium.webdriver.common.keys import Keys import requests import re import time # 初始化浏览器 driver = webdriver.Chrome('C:/Users/Paul/Desktop/ChromeDriver/chromedriver.exe') driver.get('https://magic.wizards.com/fr/mtgarena') # 登录流程 href_element = driver.find_element("xpath",'//a[@href="https://myaccounts.wizards.com/login"]') href_element.click() driver.implicitly_wait(10) uname = driver.find_element("name", "email") uname.send_keys("toto@hotmail.com") pword = driver.find_element("name", "password") pword.send_keys("toto") BoutonSeConnecter = driver.find_element("xpath",'//button[normalize-space()="Se connecter"]') BoutonSeConnecter.click() driver.implicitly_wait(10) # 记录已处理过的帖子ID,避免重复处理 processed_post_ids = set() url = 'https://www.reddit.com/r/MagicArena/new/.json' while True: try: # 每次循环重新拉取最新的Reddit帖子数据 response = requests.get(url, headers={'User-agent': 'MagicArenaCodeBot/1.0'}) response.raise_for_status() # 捕获HTTP请求错误 dict_json = response.json() except Exception as e: print(f"获取Reddit数据失败: {str(e)}") time.sleep(10) continue # 遍历最新的帖子 for child in dict_json["data"]["children"]: post_id = child["data"]["id"] if post_id in processed_post_ids: continue # 跳过已处理的帖子 processed_post_ids.add(post_id) selftext = child["data"]["selftext"] code_match = re.search(r'[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}-[A-Z0-9]{5}', selftext, re.IGNORECASE) if code_match: code = code_match.group(0).upper() # 统一转为大写,避免大小写问题 print(f"找到新兑换码: {code}") try: # 清空输入框再输入兑换码 input_field = driver.find_element("name", "code") input_field.clear() input_field.send_keys(code) BouttonEchangerCode = driver.find_element("xpath",'//button[normalize-space()="Échanger"]') BouttonEchangerCode.click() print(f"已提交兑换码: {code}") except Exception as e: print(f"提交兑换码 {code} 失败: {str(e)}") # 这里不要直接退出,避免单个错误导致整个脚本崩溃 time.sleep(10) # driver.quit() # 循环不会结束,这行代码永远不会执行到
额外说明
- User-agent尽量用更规范的名称,避免被Reddit限制访问
- 用
response.raise_for_status()可以捕获4xx/5xx的HTTP错误,比裸except更精准 - 记录帖子ID是关键,不然每次循环都会重复处理旧帖子,导致重复提交同一个兑换码
- 兑换码转为大写是因为官方兑换码通常是大写格式,避免大小写不匹配的问题
内容的提问来源于stack exchange,提问作者Paul Laguës
相关产品推荐
相关产品推荐

