制作Selenium打字测试机器人时,CSS选择器定位元素报错求助
打字测试机器人元素定位问题排查与解决
核心问题分析
你的代码主要存在以下几个可能导致定位失败的问题:
- 固定等待
time.sleep(3)不稳定,无法确保元素完全加载完成 - 使用
find_element定位多元素场景,若目标元素未加载完成会直接报错,且无法获取全部单词 - 点击Cookie弹窗后未等待测试区域元素加载
解决步骤与修正代码
1. 引入显式等待模块
替换不可靠的固定等待,使用Selenium的显式等待确保元素已加载:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC
2. 修正元素定位逻辑
- 等待Cookie按钮可点击后再执行点击操作
- 等待测试输入框出现后再定位
- 使用
find_elements获取所有单词元素,并等待元素加载完成
修正后的完整代码:
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) words = [] url = "https://typetest.io/" driver.get(url) # 等待Cookie按钮并点击(显式等待10秒) cookie_button = WebDriverWait(driver, 10).until( EC.element_to_be_clickable((By.CLASS_NAME, "fc-button-label")) ) cookie_button.click() # 等待测试输入框出现 input_field = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "test-input")) ) # 等待所有单词元素加载完成并获取 words_elements = WebDriverWait(driver, 10).until( EC.presence_of_all_elements_located((By.CSS_SELECTOR, 'span[test-word]')) ) # 提取所有单词文本 words = [element.text for element in words_elements] print(words)
3. 额外排查点
如果仍然报错,检查以下内容:
- 确认页面中单词元素的属性是否为
test-word:打开浏览器开发者工具(F12),查看单词span的属性,若实际是data-test-word,则将CSS选择器改为span[data-test-word] - 检查是否有其他弹窗或页面跳转干扰元素定位
- 确保ChromeDriver版本与本地Chrome浏览器版本匹配(
webdriver_manager通常会自动处理,但仍需确认)
内容的提问来源于stack exchange,提问作者Elitragen
相关产品推荐
相关产品推荐

