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

使用pytest编写测试用例时遇AttributeError:TestClass无get属性

解决 pytest fixture 注入导致的 AttributeError 问题

你遇到的核心问题是测试方法的参数定义错误,导致 fixture 没有被正确注入,反而把类实例(self)当成了 fixture 参数来使用——这就是为什么会出现'TestClass' object has no attribute 'get'的错误:你调用的driver.get()实际上是在调用TestClass实例的get方法,而非 Selenium WebDriver 的方法。

错误根源拆解

在类中的测试方法,第一个参数必须是self(代表当前类的实例),而你把webdriver_definition作为了第一个参数,这就造成:

  • 这个参数实际接收的是TestClass的实例,不是你定义的 fixture 返回的 WebDriver 对象
  • 当执行driver.get(baseURL)时,相当于在调用self.get(baseURL),自然会触发属性不存在的报错

修复步骤&优化方案

  1. 修正测试方法参数列表:把self作为第一个参数,再添加 fixture 参数webdriver_definition
  2. 用yield实现 fixture 的自动清理:代替测试用例里手动调用driver.quit(),让 pytest 自动处理资源回收
  3. 补全元素定位的必要参数:你之前的sd.find_element是笔误,且必须指定定位策略(如By.XPATH)

修复后的完整代码

import pytest
from selenium import webdriver
import time
from selenium.webdriver.common.by import By

class TestClass:
    @pytest.fixture(scope='function')  # 每个测试用例单独初始化driver,也可改为scope='class'实现类内复用
    def webdriver_definition(self):
        # Setup:初始化WebDriver
        driver = webdriver.Chrome(executable_path="D:/Selenium webdriver/chromedriver_win32/chromedriver.exe")
        driver.implicitly_wait(2)
        driver.maximize_window()
        print('=================Driver initialized===================')
        
        yield driver  # 将driver传递给测试用例
        
        # Teardown:测试用例执行完成后自动关闭driver
        driver.quit()
        print('=================Driver closed===================')

    def test_case(self, webdriver_definition):  # 第一个参数为self,第二个才是fixture
        driver = webdriver_definition
        baseURL = 'https://www.di.fm/'
        driver.get(baseURL)
        
        # 修正元素定位方式,必须指定定位策略
        home_button = driver.find_element(By.XPATH, "//nav[@id='side-nav']/ul//span[.='Home']")
        if home_button:
            print(f'Element "{home_button.text}" was found\n')
        else:
            print(f'Element was not found')
        home_button.click()
        time.sleep(2)

额外提示

  • 如果设置scope='class',整个测试类只会初始化一次 WebDriver,所有测试用例共用同一个实例,适合类内测试逻辑关联性强的场景
  • 尽量避免用time.sleep(),可以改用WebDriverWait实现显式等待,让测试更稳定

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:22:34