You need to enable JavaScript to run this app. 使用Puppeteer操作Codeforces时无法编辑textarea且报错如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

使用Puppeteer操作Codeforces时无法编辑textarea且报错如何解决?

问题解决思路

错误原因梳理

  • Promise.all用法错误:点击操作和导航等待需要同时传入Promise.all,不能提前await点击操作。点击触发导航后页面上下文销毁,后续未执行的waitForNavigation就会抛出Execution context was destroyed报错。
  • textarea输入失效:ElementHandle.type()是异步方法,你没有加await等待执行完成,输入逻辑还没跑完就读取内容、触发提交,自然看不到输入效果也拿不到值。
  • 提交逻辑无等待:最后提交的Promise.all没有加await,且内部同样存在提前await点击的问题,提交后的跳转逻辑完全失效。

修正后可用代码

const pupp = require('puppeteer');
const email = '你的Codeforces账号';
const password = '你的Codeforces密码';

(async () => {
  const url = "https://codeforces.com/enter?back=%2F"
  const browser = await pupp.launch({ headless: false }); // 调试阶段建议开有头模式观察操作流程
  const page = await browser.newPage();
  await page.goto(url, {
      waitUntil: 'load',
      timeout: 0
  });

  // 登录逻辑
  await page.type('#handleOrEmail', email);
  await page.type('#password', password);
  await Promise.all([
    page.click('#enterForm > table > tbody > tr:nth-child(4) > td > div:nth-child(1) > input'),
    page.waitForNavigation({ waitUntil: 'networkidle0' }),
  ])

  // 跳转到题目集页
  await Promise.all([
    page.click('#body > div.roundbox.menu-box > div.menu-list-container > ul > li:nth-child(5) > a'),
    page.waitForNavigation({ waitUntil: 'networkidle0' }),
  ])

  // 跳转到提交页
  await Promise.all([
    page.click('#pageContent > div.second-level-menu > ul:nth-child(3) > li:nth-child(3) > a'),
    page.waitForNavigation({ waitUntil: 'networkidle0' }),
  ])

  // 填写提交信息
  await page.type('#pageContent > form > table > tbody > tr:nth-child(1) > td:nth-child(2) > input', '4A');
  // 等待textarea加载完成再操作,避免元素未渲染报错
  const txt = await page.waitForSelector('#editor > textarea', { visible: true });
  await txt.type('hello') // 加await等待输入完成
  console.log('输入的代码内容:', await page.$eval('#editor > textarea', e => e.value))

  // 提交代码并等待跳转
  await Promise.all([
    page.click('#pageContent > form > table > tbody > tr:nth-child(6) > td > div > div > input'),
    page.waitForNavigation({ waitUntil: 'networkidle0' })
  ])

  // 跳转到我的提交状态页
  await page.goto('https://codeforces.com/problemset/status?my=on', { waitUntil: 'networkidle0' });
  // 等待状态表格渲染,可适当延长超时时间等待判题完成
  await page.waitForSelector('table.status-frame-datatable tr:nth-child(2) td.verdict', { timeout: 15000 });
  // 读取最新提交的Verdict内容
  const verdict = await page.$eval('table.status-frame-datatable tr:nth-child(2) td.verdict', el => el.textContent.trim());
  console.log('提交判题结果:', verdict);

  await browser.close();
})();

额外注意事项

  • 如果需要获取最终判题结果,可加定时循环查询Verdict内容,避免刚提交时拿到In queue、Running这类中间状态
  • 选择器尽量不使用完全匹配的层级结构,Codeforces前端结构变更后会导致选择器失效,可优先用id、属性等稳定特征定位元素

内容的提问来源于stack exchange,提问作者user14066647

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.20 06:54:04