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

使用Python unittest+Selenium做登录测试遇AttributeError问题求助

解决unittest中AttributeError: 'KenLogin' object has no attribute 'driver'的问题

兄弟,你这个错误的根源真的很容易忽略——你把unittest的初始化方法名称写错了!

你代码里写的是setup(),但unittest框架规定的测试类初始化方法必须是setUp()(注意是大写的U)。因为方法名不匹配,这个初始化方法根本没被unittest框架自动调用,导致self.driver完全没有被创建,后面的test_login和tearDown方法里访问self.driver自然就会抛出「属性不存在」的错误。

修改后的正确代码

只需要把setup()改成setUp()就可以解决这个问题:

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys

class KenLogin(unittest.TestCase):
    # 修正方法名:setup -> setUp(大写U)
    def setUp(self):
        # self.driver = webdriver.Chrome(executable_path='E:\\Learning\\chromedriver.exe')
        self.driver = webdriver.Firefox()

    def test_login(self):
        driver = self.driver
        driver.get("http://qa.kenzen.com")
        username = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[2]/form/div[1]/input")
        password = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[2]/form/div[2]/input")
        username.send_keys("pardeepk@clovity.com")
        password.send_keys("Kenzen@123")
        button = driver.find_element_by_xpath("/html/body/div[1]/div/div[2]/div/div[2]/form/button")
        button.click()
        print("Login Pass")

    def tearDown(self):
        self.driver.close()

if __name__ == "__main__":
    unittest.main()

额外小提示

  • 如果你用Firefox的话,要确保geckodriver已经正确配置到系统环境变量里,或者在初始化时指定executable_path,不然可能会出现浏览器启动失败的新错误
  • 尽量不要用这种全路径的XPath,一旦页面结构有微小变化,定位就会失效,建议换成更稳定的定位方式,比如通过元素的id、name或者class属性来定位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 06:43:45