运行 按顺序在 python 脚本中运行

Running functions in a python script in order

我正在使用 selenium webdriver 创建一个用 python 编写的测试套件。但是,当我 运行 我的测试时,我得到的错误是: 'PythonOrgSearch' object has no attribute 'driver'

我很确定这是因为测试没有按顺序 运行 进行,所以驱动程序在测试完成之前就关闭了。我之前也遇到过错误:"Tried to run command without establishing a connection",我认为这也表明测试没有按顺序 运行 进行,所以驱动程序没有启动?我不确定这是否准确,只是我最好的猜测。我的代码如下所示:

import unittest
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import os
import time
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.action_chains import ActionChains
from urllib.request import urlopen
from html.parser import HTMLParser


gecko = os.path.normpath(os.path.join(os.path.dirname(__file__), 'geckodriver'))
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')
driver = webdriver.Firefox(firefox_binary=binary, executable_path=gecko+'.exe')


class PythonOrgSearch(unittest.TestCase):

#sets up driver to run tests
    def setUp(self):
        self.driver = driver
        self.driver.start()

    def test_opens(self):
        driver.get("url.com")
        driver.find_element_by_id('username').send_keys('user')
        driver.find_element_by_id('password').send_keys('pass')
        driver.find_elements_by_css_selector("button[type='submit']")[0].click()
        time.sleep(2);
        self.assertIn("title", driver.title)

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

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

编辑:我在每个函数的开头添加了 driver=self.driver

您似乎从未初始化 self.driver 变量。您是否在 PythonOrgSearch class 中声明了一个 __init__ 方法?

好的,我使用变通方法解决了问题。 虽然函数没有按顺序 运行,但它们每次都按相同的顺序执行 运行,所以我把 driver.quit() 放在 运行 函数的末尾最后的。我还(在编辑中)将 driver=self.driver 添加到每个函数的顶部。正如其他发帖者所回应的那样,最好在 class.

中放置一个 init 方法

此解决方案可能不是最佳做法,但确实有效。对于有类似问题的人,此线程中的其他回复确实提供了对该问题的一些见解,我只是没有找到解决我的问题的人。