Python+Selenium定位JS登录失败提示:By.Class不存在如何按class等待元素?
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

