求助:使用Selenium Python无法获取10fastfingers测试全部单词
解决10fastfingers打字测试中Selenium只能获取可见单词的问题
问题原因
10fastfingers的单词容器#words里,未显示的单词会被CSS设置为不可见(比如visibility: hidden),而Selenium的.text属性只会返回元素可见的文本内容,所以你只能拿到页面上显示的前几个单词。
解决方法
不要直接获取容器的文本,而是遍历#words下的所有<span>子元素(每个单词对应一个span标签),通过get_attribute('textContent')获取每个单词的文本——这个方法能拿到元素的全部文本,不管它是否可见。
修改后的完整代码:
from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By import time options = webdriver.ChromeOptions() options.add_experimental_option('detach', True) driver = webdriver.Chrome(options=options) driver.get(url='https://10fastfingers.com/typing-test/english') time.sleep(2) # 关闭隐私弹窗 driver.find_element(By.XPATH, '//*[@id="CybotCookiebotDialogBodyButtonDecline"]').click() time.sleep(2) # 遍历所有单词span元素,提取每个单词的文本 word_elements = driver.find_elements(By.CSS_SELECTOR, '#words span') words = [elem.get_attribute('textContent') for elem in word_elements] # 提前定位输入框,避免重复查找 input_box = driver.find_element(By.ID, 'inputfield') for word in words: input_box.send_keys(word) input_box.send_keys(Keys.SPACE)
额外优化建议
- 把固定的
time.sleep()换成Selenium的显式等待,能让代码更稳定,避免因页面加载慢导致的报错:from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待隐私弹窗按钮可点击后再点击 WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.ID, 'CybotCookiebotDialogBodyButtonDecline')) ).click() # 等待单词容器加载完成 WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, 'words')) )
内容的提问来源于stack exchange,提问作者LiorMorali
相关产品推荐
相关产品推荐

