selenium获取元素 出现的错误AttributeError: ‘TestPage‘ object has no attribute ‘driver‘

目录

错误收集

错误分析

解决办法

运行结果


错误收集

D:\Program\Util\python.exe "D:/Program/myUtil/PyCharm 2024.3.5/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py" --target testfeishu.py::TestPage

Testing started at 8:04 ...

Launching pytest with arguments testfeishu.py::TestPage --no-header --no-summary -q in C:\Users\Administrator\PycharmProjects\PoPage

============================= test session starts =============================

collecting ... collected 1 item

testfeishu.py::TestPage::test_login_001

============================== 1 failed in 0.37s ==============================

FAILED [100%]你好啊

testfeishu.py:23 (TestPage.test_login_001)

self = <testfeishu.TestPage object at 0x000001D93AB3E710>

def test_login_001(self):

print("你好啊")

获取元素 ==》通过id定位

> login_button = self.driver.find_element(by=By.CSS_SELECTOR, value="div > a[class='button-login']")

^^^^^^^^^^^

E AttributeError: 'TestPage' object has no attribute 'driver'

testfeishu.py:27: AttributeError

Process finished with exit code 1

错误分析

查看代码,发现我们写的前置处理函数是setup , 但是这个是当前最新版本的selenium 这个方法已经被修改为setup_method,teardown也已经被修改为teardown_method

复制代码
def setup(self):
    self.driver = webdriver.Chrome()

解决办法

修改前置处理器的方法

def setup_class(self)

复制代码
class TestPage:

    def setup_method(self):
        self.driver = webdriver.Chrome()

运行结果

可以看到报错已经解决了

运行结果收集

D:\Program\Util\python.exe "D:/Program/myUtil/PyCharm 2024.3.5/plugins/python-ce/helpers/pycharm/_jb_pytest_runner.py" --target testfeishu.py::TestPage.test_login_001

Testing started at 8:15 ...

Launching pytest with arguments testfeishu.py::TestPage::test_login_001 --no-header --no-summary -q in C:\Users\Administrator\PycharmProjects\PoPage

============================= test session starts =============================

collecting ... collected 1 item

testfeishu.py::TestPage::test_login_001

============================== 1 passed in 6.85s ==============================

PASSED [100%]你好啊

已经获取了驱动

Process finished with exit code 0

相关推荐
TF男孩7 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
该用户已不存在12 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust
站大爷IP14 小时前
Java调用Python的5种实用方案:从简单到进阶的全场景解析
python
用户83562907805119 小时前
从手动编辑到代码生成:Python 助你高效创建 Word 文档
后端·python
c8i19 小时前
python中类的基本结构、特殊属性于MRO理解
python
liwulin050620 小时前
【ESP32-CAM】HELLO WORLD
python
Doris_202320 小时前
Python条件判断语句 if、elif 、else
前端·后端·python
Doris_202320 小时前
Python 模式匹配match case
前端·后端·python
这里有鱼汤21 小时前
Python量化实盘踩坑指南:分钟K线没处理好,小心直接亏钱!
后端·python·程序员
大模型真好玩21 小时前
深入浅出LangGraph AI Agent智能体开发教程(五)—LangGraph 数据分析助手智能体项目实战
人工智能·python·mcp