Python中Selenium模块'find_element'属性错误的解决难题
解决Selenium 4.9.1中
selenium.webdriver has no attribute find_element错误 错误核心原因
你存在两个关键问题:
find_element是**WebDriver实例(即你创建的browser对象)**的方法,不是webdriver模块的属性,直接调用webdriver.find_element必然触发报错。- 代码中使用了
By.CLASS_NAME但未导入By类。 - 存在重复导入的冗余代码,虽不影响运行,但需清理。
修正后的完整代码
from selenium import webdriver from selenium.webdriver.chrome.service import Service from webdriver_manager.chrome import ChromeDriverManager from selenium.webdriver.common.action_chains import ActionChains # 必须导入By类才能使用By.CLASS_NAME这类定位方式 from selenium.webdriver.common.by import By # 初始化浏览器实例 browser = webdriver.Chrome(service=Service(ChromeDriverManager().install())) browser.maximize_window() browser.get("https://www.asurascans.com/?s=Beast+Burn") # 改用browser实例调用find_element方法 element = browser.find_element(By.CLASS_NAME, "surprise") action = ActionChains(browser) action.click(on_element=element) action.perform() browser.quit() print("successful run!")
额外优化建议
如果目标元素加载较慢,直接调用find_element可能出现找不到元素的错误,建议添加显式等待提升稳定性:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # 等待元素出现,最多等待10秒 element = WebDriverWait(browser, 10).until( EC.presence_of_element_located((By.CLASS_NAME, "surprise")) )
内容的提问来源于stack exchange,提问作者user21790159
相关产品推荐
相关产品推荐

