如何修复“AttributeError: 'WebElement'对象无'find_element_class_name'属性”错误?
解决Selenium中AttributeError: 'WebElement' object has no attribute 'find_element_class_name'的问题
嘿,这个问题我之前踩过同款坑!报错的核心原因特别直白——你写错了WebElement的方法名称,少了关键的_by_部分。
错误原因解析
Selenium的WebElement对象里,通过类名查找元素的方法是find_element_by_class_name(),而不是你写的find_element_class_name()。正是这个拼写小失误导致了AttributeError,因为Python找不到这个不存在的方法名。
修正方案1:修正旧版方法名
直接把错误的方法名改成正确的find_element_by_class_name()即可,修正后的代码如下:
try: main = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "main"))) articles = main.find_elements_by_tag_name("article") for article in articles: # 修正方法名,添加_by_ header = article.find_element_by_class_name("entry-title") print(header.text) finally: driver.quit()
修正方案2:使用Selenium 4+推荐的新API
从Selenium 4版本开始,find_element_by_*这类旧方法已经被标记为过时,官方更推荐使用By类配合find_element()/find_elements()的写法,这种写法更统一规范,也便于后续维护。修正后的代码如下:
# 确保导入了必要的模块 from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC try: main = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "main"))) # 用新写法查找所有article元素 articles = main.find_elements(By.TAG_NAME, "article") for article in articles: # 用新写法查找标题元素 header = article.find_element(By.CLASS_NAME, "entry-title") print(header.text) finally: driver.quit()
额外建议:处理可能的元素不存在情况
如果页面中存在没有entry-title类的article元素,循环会因为找不到元素而抛出异常中断。可以添加异常处理来避免这种情况:
# 记得导入异常类 from selenium.common.exceptions import NoSuchElementException try: main = WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.ID, "main"))) articles = main.find_elements(By.TAG_NAME, "article") for article in articles: try: header = article.find_element(By.CLASS_NAME, "entry-title") print(header.text) except NoSuchElementException: print("跳过无标题的文章") continue finally: driver.quit()
内容的提问来源于stack exchange,提问作者Markus nuan
相关产品推荐
相关产品推荐

