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

Python+Selenium定位JS登录失败提示:By.Class不存在如何按class等待元素?

Fixing the "By.Class Doesn't Exist" Issue for Waiting on JS-Generated Login Error Messages

Got it, let's work through this problem together. The core issue here is a small syntax mix-up with Selenium's By class, plus making sure we properly wait for that dynamically loaded error message to appear.

First things first: there's no By.Class in Selenium's Python bindings—you're looking for By.CLASS_NAME instead. That's the correct constant to use when targeting elements by their class attribute.

Since your error message is generated by JavaScript and takes a moment to load, using WebDriverWait with an expected condition is exactly the right approach. Here's a complete, ready-to-use code example:

# Import required modules
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

# Initialize your driver (adjust based on your browser of choice)
driver = webdriver.Chrome()

# Perform your login flow here (enter username/password, click login button)
# ...

# Wait up to 10 seconds for the error message element to load
try:
    # Replace "your-error-class" with the actual class name of your target element
    error_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "your-error-class"))
    )
    # Extract and use the error text once the element is found
    print("Login failed with message:", error_element.text)
except TimeoutException:
    print("Timeout: Login error message didn't appear within 10 seconds")

# Clean up the driver instance
driver.quit()

Quick heads-up if your element has multiple classes:

If the error element's class attribute includes spaces (like class="alert login-error"), By.CLASS_NAME won't work with the full string—spaces mean multiple separate classes. In that case, switch to a CSS selector instead:

# Using CSS selector to target elements with multiple classes
error_element = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, ".alert.login-error"))
)

That should fix the "By.Class doesn't exist" error and reliably wait for your dynamically generated login failure message.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 08:07:57