Python - 在类中传递函数的参数

时间:2015-08-20 23:09:16

标签: python firefox selenium selenium-webdriver

有没有人可以帮我制作以下代码?


    import time
    from selenium import webdriver
    from selenium.webdriver.common.keys import Keys
    #
    class DataddoMobileTestFirefox():
        #
        def setUp_and_login(self, browser):
            '''
            Supported browsers are: firefox; chrome
            '''
            global driver
            global email
            global password
            global login_btn
            #
            if browser == firefox:
                driver = webdriver.Firefox()
            elif browser == chrome:
                driver = webdriver.Chrome('/Library/Chromedriver/chromedriver')
            else:
                print('Browser not recognized, exiting...')
                exit()
    #
    #
    # Execute the module
    if __name__ == '__main__':
        DataddoMobileTestFirefox().setUp_and_login(firefox)

当我执行模块时,我收到以下错误消息:


    Traceback (most recent call last):
      File "DataddoMobileFirefox.py", line 26, in 
        DataddoMobileTestFirefox().setUp_and_login(firefox)
    NameError: name 'firefox' is not defined

我相信我接近目标,一些暗示会对我有所帮助 非常感谢提前。

1 个答案:

答案 0 :(得分:2)

您的模块中未定义

firefox。我认为你希望它是一个变量。

您可以改用字符串:

DataddoMobileTestFirefox().setUp_and_login('firefox')

然后在您的setUp_and_login()方法中:

if browser == 'firefox':
    driver = webdriver.Firefox()
else browser == 'chrome':
    driver = webdriver.Chrome('/Library/Chromedriver/chromedriver')

但可能最好在班级__init__()中进行设置。考虑到您的类名为DataddoMobileTestFirefox,可以预期它仅适用于Firefox,因此无需通过将其传递给setUp_and_login()来识别浏览器。只需在__init__()中创建一个驱动程序实例:

from selenium import webdriver

class DataddoMobileTestFirefox():
    def __init__(self, driver):
        self.driver = webdriver.Firefox()

    def some_method(self):
        self.driver.do_something()

现在,您可以从类中的其他方法访问驱动程序,而无需使用global