Python Selenium自动化10fastfingers脚本输入初始单词后崩溃的排查与解决
问题描述
我编写了一个自动化脚本用于完成10fastfingers的英文打字测试,但脚本在输入页面初始显示的单词集后就崩溃,无法继续输入后续内容。
最初的错误代码
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time try: driver = webdriver.Firefox() driver.get("https://10fastfingers.com/typing-test/english") # Wait for the page to fully load time.sleep(6) # Find the text input element on the page text_input = driver.find_element("id", "inputfield") current_word = driver.find_element("id", "row1") print(type(driver)) # <-- Add this line # Type the words into the input field while True: text_to_type = current_word.text for character in text_to_type: text_input.send_keys(character) time.sleep(0.1) # Check if the next sibling element exists next_word = current_word.find_element_by_xpath("following-sibling::span[1]") if not next_word: break current_word = next_word # Submit the form to complete the typing test text_input.send_keys(Keys.RETURN) except Exception as e: print("An error occurred:", e) finally: # Close the web browser driver.quit()
尝试过的无效解决方案
- 模拟人类输入延迟:误以为浏览器拦截自动输入,给每个字符和单词添加随机延迟,但问题依旧:
for word in text_to_type: for character in word: text_input.send_keys(character) time.sleep(random.uniform(0.05, 0.1)) text_input.send_keys(Keys.SPACE) time.sleep(random.uniform(0.5, 1.0))
- 重新获取单词块:猜测页面输入后会动态更新内容,尝试循环获取
#row1下的span元素,但没有效果:
while True: # Get the next word to type word_elements = driver.find_elements("css selector", "#row1 span") if not word_elements: break word = word_elements[0].text
最终解决代码
问题出在元素定位逻辑上,最初通过row1和兄弟元素遍历的方式无法适配页面动态更新的结构。改用//span[@wordnr]这个XPath可以直接获取所有带wordnr属性的单词元素,这些元素是页面预加载的全部测试单词,无需处理后续的动态更新。
from selenium import webdriver from selenium.webdriver.common.keys import Keys import time try: driver = webdriver.Firefox() driver.get("https://10fastfingers.com/typing-test/english") # 等待页面完全加载 time.sleep(6) # 定位输入框 text_input = driver.find_element("id", "inputfield") # 获取所有带wordnr属性的单词元素(即所有需要输入的单词) words = driver.find_elements("xpath", "//span[@wordnr]") # 逐个输入单词 for word in words: text_to_type = word.text for character in text_to_type: text_input.send_keys(character) time.sleep(0) text_input.send_keys(" ") time.sleep(0) # 提交完成测试 text_input.send_keys(Keys.RETURN) except Exception as e: print("发生错误:", e) # finally: # 关闭浏览器 # driver.quit()
关键修复点
- 放弃通过
row1和兄弟元素遍历的方式,直接定位所有带wordnr属性的span元素,一次性获取全部测试单词,避开页面动态更新带来的元素定位问题。 - 移除不必要的延迟(或设置为0),确保脚本快速执行的同时,避免因延迟导致元素状态变化引发的异常。
内容的提问来源于stack exchange,提问作者Rashad Aliyev
相关产品推荐
相关产品推荐

