‘NoneType‘ object has no attribute ‘...‘

‘NoneType’ object has no attribute ‘get’;
‘NoneType’ object has no attribute ‘switch_to’;
‘NoneType’ object has no attribute ‘find_element_by_name’;
等等这些错误,其实就是识别不出来

我报这个错的原因就是:没有声明driver是个全局变量【get,switch_to,find_element_by_name都是driver的方法】
更改之前的代码:

import unittest
from time import sleep
from selenium import webdriver

driver=None
class unitTestMock(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        driver = webdriver.Chrome()
        driver.maximize_window()
        print("运行setUpClass...")

    def setUp(self):
        print("运行setUp...")

    def test1_WebTours(self):
        driver.get("http://localhost:1080/WebTours/")
        sleep(3)
        
   def test2_ClickSignOff(self):
       driver.switch_to.default_content()
       driver.switch_to.frame("body")
       driver.switch_to.frame("navbar")
       driver.find_element_by_xpath("//img[@alt=\"SignOff Button\"]")

    def tearDown(self):
        print("运行tearDown...")

    @classmethod
    def tearDownClass(cls):
        driver.quit()
        print("运行tearDownClass...")

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

更改之后的代码:

import unittest
from time import sleep
from selenium import webdriver

driver=None
class unitTestMock(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
    	global driver
        driver = webdriver.Chrome()
        driver.maximize_window()
        print("运行setUpClass...")

    def setUp(self):
        print("运行setUp...")

    def test1_WebTours(self):
        driver.get("http://localhost:1080/WebTours/")
        sleep(3)
        
    def test2_ClickSignOff(self):
       driver.switch_to.default_content()
       driver.switch_to.frame("body")
       driver.switch_to.frame("navbar")
       driver.find_element_by_xpath("//img[@alt=\"SignOff Button\"]")

    def tearDown(self):
        print("运行tearDown...")

    @classmethod
    def tearDownClass(cls):
        driver.quit()
        print("运行tearDownClass...")

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

差别就是在 setUpClass 方法中增加了一个 global driver。没有global driver,它就认为driver只是你定义的一个变量,自然也就没有webdriver的那些方法,即使你调用了也识别不出来。

你可能感兴趣的:(unitTest)