首页 > 解决方案 > 如何在 Python 中使用对象在类创建中传递参数?

问题描述

我正在尝试为我的 selenium 自动化脚本保存 cookie,以避免登录过程以备将来自动化。

这是工作正常的原始脚本

class SeleniumDriver(object):
    def __init__(
        self,
        # chromedriver path
        driver_path='chromedriver.exe',
        # pickle file path to store cookies
        cookies_file_path = 'cookies.pkl',
        # list of websites to reuse cookies with
        cookies_websites=["https://website.com"] # I would like to replace this website by an argument

    ):
        self.driver_path = driver_path
        self.cookies_file_path = cookies_file_path
        self.cookies_websites = cookies_websites
        #PREVIOUS VERSION WITH NORMAL CHROME chrome_options = webdriver.ChromeOptions()
        chrome_options = uc.ChromeOptions()
        #PREVIOUS VERSION WITH NORMAL CHROME self.driver = webdriver.Chrome(
        self.driver = uc.Chrome(
            executable_path=self.driver_path,
            options=chrome_options
        )
        try:
            # load cookies for given websites
            cookies = pickle.load(open(self.cookies_file_path, "rb"))
            for website in self.cookies_websites:
                self.driver.get(website)
                for cookie in cookies:
                    self.driver.add_cookie(cookie)
                self.driver.refresh()
        except Exception as e:
            # it'll fail for the first time, when cookie file is not present
            logger.error(str(e))
            logger.error("ERROR : Error loading cookies")

    def save_cookies(self):
        # save cookies
        cookies = self.driver.get_cookies()
        pickle.dump(cookies, open(self.cookies_file_path, "wb"))

    def close_all(self):
        # close all open tabs
        if len(self.driver.window_handles) < 1:
            return
        for window_handle in self.driver.window_handles[:]:
            self.driver.switch_to.window(window_handle)
            self.driver.close()

    def quit(self):
        self.save_cookies()
        self.close_all()
        self.driver.quit()


selenium_object = SeleniumDriver()
driver = selenium_object.driver

您可以在创建对象期间的代码中看到,网站“https://website.com”的网址用于为该网站创建cookie。

如果明天,我将我的脚本用于“https://anotherwebsite.com”,我需要将网站作为参数传递,例如:

class SeleniumDriver(object,website): # the variable website is passed as argument in class creation
    ....

website="https://anotherwebsite.com"
selenium_object = SeleniumDriver(website)

我的问题是我总是有这个错误输出:

NameError: name 'website' is not defined

这是不起作用的完整代码:

class SeleniumDriver(object,website):
    def __init__(
        self,
        # chromedriver path
        driver_path='chromedriver.exe',
        # pickle file path to store cookies
        cookies_file_path = 'cookies.pkl',
        # list of websites to reuse cookies with
        cookies_websites=[website]

    ):
        self.driver_path = driver_path
        self.cookies_file_path = cookies_file_path
        self.cookies_websites = cookies_websites
        #PREVIOUS VERSION WITH NORMAL CHROME chrome_options = webdriver.ChromeOptions()
        chrome_options = uc.ChromeOptions()
        #PREVIOUS VERSION WITH NORMAL CHROME self.driver = webdriver.Chrome(
        self.driver = uc.Chrome(
            executable_path=self.driver_path,
            options=chrome_options
        )
        try:
            # load cookies for given websites
            cookies = pickle.load(open(self.cookies_file_path, "rb"))
            for website in self.cookies_websites:
                self.driver.get(website)
                for cookie in cookies:
                    self.driver.add_cookie(cookie)
                self.driver.refresh()
        except Exception as e:
            # it'll fail for the first time, when cookie file is not present
            logger.error(str(e))
            logger.error("ERROR : Error loading cookies")

    def save_cookies(self):
        # save cookies
        cookies = self.driver.get_cookies()
        pickle.dump(cookies, open(self.cookies_file_path, "wb"))

    def close_all(self):
        # close all open tabs
        if len(self.driver.window_handles) < 1:
            return
        for window_handle in self.driver.window_handles[:]:
            self.driver.switch_to.window(window_handle)
            self.driver.close()

    def quit(self):
        self.save_cookies()
        self.close_all()
        self.driver.quit()

website="https://mywebsite.com"
selenium_object = SeleniumDriver(website)
driver = selenium_object.driver

当我运行这段代码时,我得到这个错误输出:

 class SeleniumDriver(object,website):
NameError: name 'website' is not defined

标签: pythonpython-3.xclassobject

解决方案


推荐阅读