Python - Selenium - 单线程到多线程

Python - Selenium - Single thread to multiple threads

我有一个用 Python 和 Selenium 制作的自动化项目,我正在尝试 运行 并行使用多个浏览器。

当前工作流程:

所描述的工作流程是打开一些浏览器,一个一个地打开,直到打开所有需要的浏览器。

我的代码包含几个 classes:浏览器和 Ui。

用 Ui class 实例化的对象包含一个在某些时候执行以下代码的方法:

    for asset in Inventory.assets:
        self.browsers[asset] = ui.Browser()
        # self.__open_window(asset)            # if it is uncommented, the code is working properly without multi threading part; all the browsers are opened one by one

    # try 1
    # threads = []
    # for asset in Inventory.assets:
    #     threads.append(Thread(target=self.__open_window, args=(asset,), name=asset))
    # for thread in threads:
    #     thread.start()

    # try 2
    # with concurrent.futures.ThreadPoolExecutor() as executor:
    #     futures = []
    #     for asset in Inventory.assets:
    #         futures.append(executor.submit(self.__open_window, asset=asset))
    #     for future in concurrent.futures.as_completed(futures):
    #         print(future.result())

当self.__open_window在线程内执行时出现问题。我收到一个与 Selenium 相关的错误,例如:'NoneType' object has no attribute 'get',当 self.driver.get(url) 从浏览器 class 调用时.

def __open_window(self, asset):
    self.interface = self.browsers[asset]
    self.interface.open_browser()

在 class 浏览器中:

def open_browser(self, driver_path=""):
    # ...
    options = webdriver.ChromeOptions()
    # ...
    #
    web_driver = webdriver.Chrome(executable_path=driver_path, options=options)
    #
    self.driver = web_driver
    self.opened_tabs["default"] = web_driver.current_window_handle
    #
    # ...

def get_url(self, url):
    try:
        self.driver.get(url)      # this line cause problems ...
    except Exception as e:
        print(e)

我的问题是: 为什么我在多线程环境中有这个问题? 我应该怎么做才能使代码正常工作?

谢谢

我发现了错误,这是因为错误的对象引用。 修改后代码运行良好。

我在 __open_window 更新了以下行:

    def __open_window(self, asset, browser):
        browser.interface = self.browsers[asset]
        browser.interface.open_browser()

并在 # 中尝试 1 个代码部分:

threads.append(Thread(target=self.__open_window, args=(asset, browser, ), name=asset))