You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现单词列表刷新与输入框按键发送?Selenium打字测试Bot问题

解决10fastfingers芬兰语打字测试Bot的动态单词列表问题

原代码核心问题

  • 用固定索引k访问更新后的单词列表,会触发索引越界:每次输入单词后,页面会移除已输入的单词并加载新单词,原列表的索引逻辑完全失效。
  • 依赖time.sleep等待元素,稳定性极差,页面加载延迟时会直接导致操作失败。
  • 循环条件k != 200不合理,未考虑测试提前结束的场景。

修正后的代码

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.chrome.options import Options
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

options = Options()
options.add_experimental_option("detach", True)

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()), options=options)

collected_words = []
target_word_count = 200

url = "https://10fastfingers.com/typing-test/finnish"
driver.get(url)

# 处理Cookie弹窗,确保元素可点击后再操作
wait = WebDriverWait(driver, 10)
cookie_button = wait.until(EC.element_to_be_clickable((By.CLASS_NAME, "CybotCookiebotDialogBodyButton")))
cookie_button.click()

# 等待输入框和单词容器加载完成
input_field = wait.until(EC.presence_of_element_located((By.ID, "inputfield")))
words_container = wait.until(EC.presence_of_element_located((By.ID, "words")))

while len(collected_words) < target_word_count:
    try:
        # 获取当前显示的所有单词
        current_words = words_container.text.split()
        if not current_words:
            break  # 测试结束,无剩余单词
        
        # 取当前列表第一个单词输入
        current_word = current_words[0]
        collected_words.append(current_word)
        
        input_field.send_keys(current_word)
        input_field.send_keys(Keys.SPACE)
        
        # 等待已输入的单词从DOM中移除,确保列表更新完成
        wait.until(EC.staleness_of(words_container.find_element(By.XPATH, f"//span[text()='{current_word}']")))
        # 重新定位单词容器,避免DOM更新导致元素失效
        words_container = wait.until(EC.presence_of_element_located((By.ID, "words")))
        
    except Exception as e:
        print(f"操作出错:{e}")
        break

print(f"收集到的单词总数:{len(collected_words)}")
print(f"单词列表:{collected_words}")
driver.quit()

关键改动说明

  • 动态取词逻辑:每次输入当前单词列表的第一个元素,适配页面自动移除已输入单词的机制,彻底避免索引越界问题。
  • 显式等待替代固定休眠:用WebDriverWait结合预期条件判断元素状态,比time.sleep更适配页面加载速度,提升稳定性。
  • 合理循环条件:以收集到的单词数量作为循环终止条件,同时处理测试提前结束的场景。
  • DOM更新适配:每次输入后等待已输入单词从DOM中移除,并重新定位单词容器,避免页面DOM更新导致的元素失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:05:32