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

相关推荐
qq_402605656 小时前
python爬虫(一) ---- 静态html数据抓取
爬虫·python·html
加油20196 小时前
爬虫框架: selenium API使用介绍
爬虫·selenium·测试工具
2401_831501736 小时前
Python学习之Day05学习(定制数据对象,面向对象)
前端·python·学习
蔗理苦6 小时前
2025-10-06 Python不基础 15——metaclass
python·metaclass
带娃的IT创业者6 小时前
Function Call实战效果:准确率提升86%背后的数据与思考,兼谈MCP的未来
人工智能·python·function call·性能分析·技术趋势·mcp·roi
可触的未来,发芽的智生7 小时前
触摸未来2025.10.05:悟神经网络符号之伤,拥抱声音的宇宙
人工智能·python·神经网络·算法·架构
_bong7 小时前
python评估算法性能
数据结构·python·算法
儒雅芝士7 小时前
BIT*算法
python
蒋星熠7 小时前
用 CodeBuddy CLI + Prompt,从零到可运行:前后端混合管理系统的高效实战
人工智能·python·机器学习·prompt·codebuddy code·无界生成力·ai cli
Nina_7177 小时前
第一章——了解prompt以及一些基础技巧方法
人工智能·python