Python-Selenium-单线程到多线程



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

当前工作流程:

  • 打开浏览器进行手动登录
  • 保存cookie以备日后使用
  • 在循环中,打开其他浏览器,在每个新打开的浏览器中加载保存的会话

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

我的代码包含几个类:Browser和Ui。

用Ui类实例化的对象包含一个方法,该方法在某个时刻执行以下代码:

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())

问题出现在自我__open_window在线程中执行。我得到了一个与Selenium相关的错误,类似于:当从Browser类调用self.driver.get(url(时,"NoneType"对象没有属性"get"。

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

类内浏览器:

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()

并且在#try 1代码段中:

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

最新更新