[ENG]
Hello! I recently started learning how to work with browsers in python and ran into a problem.
I can’t create multithreading of browser sessions using undetected chromedriver. In my code, sessions are started one after the other, but they must be started at the same time. I tried to do this using GPT chat, but it didn’t help at all:(
Here is the source code, with basic functionality.Thank you in advance!
[RUS]
Здравствуйте! Совсем недавно начал изучать работу с браузерами в пайтон и столкнулся с проблемой.
Не могу создать многопоточность сессий браузеров, используя undetected chromedriver. В моём коде сессии запускаются друг за другом, но должны запускаться одновременно. Пытался сделать это с помощью чата GPT, но он совсем не помог 🙁
Соурс код, с базовым функционалом. Находится ниже! Заранее благодарю!
import time
import undetected_chromedriver as uc
from rich import print
while True:
print("n[green]❤️[white] How much sessions :")
session_count = int(input("==> Enter the response in the console : "))
print("n[green]❤️[white] Select the site you want to [green]visit [white]: [green] example / example_1 / example_2")
platform = input("==> Enter the response in the console : ")
if platform in ["example", "example_1", "example_2"]:
break
else:
print("n❗️ [white]ENTER [red]example[white] or [red]example_1[white] or [red]example_2")
# If ok
print(f"[green]==> [white]The site is selected: [green]{platform}")
# Start session
number_of_session = 0
for i in range(session_count):
# Launching the browser
options = uc.ChromeOptions()
options.add_argument("--window-size=518,600")
driver = uc.Chrome(options=options)
if platform == "example":
driver.get('https://example.com/')
elif platform == "example_1":
driver.get('https://example.com/')
elif platform == "example_2":
driver.get('https://example.com/')
print("Session numer ", number_of_session + 1, "has launched")
number_of_session += 1
# We display a completion message
print("All sessions are running")
while True:
time.sleep(1)
GPT chat created an error code:
It is not possible to create a file because it already exists :
C:UsersMeappdataroamingundetected_chromedriverundetectedchromedriver-win32chromedriver.exeSession number 2 has launched
Exception in thread Thread-1 (run_session):
Traceback (most recent call last):
File “C:UsersALEXAppDataLocalProgramsPythonPython312Libthreading.py”, line 1073, in _bootstrap_inner
self.run()
File “C:UsersALEXAppDataLocalProgramsPythonPython312Libthreading.py”, line 1010, in run
self._target(*self._args, **self.kwargs)
File “c:UsersALEXDesktopSENDERASK.py”, line 10, in run_session
driver = uc.Chrome(options=options, use_subprocess=True)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “C:UsersALEXAppDataLocalProgramsPythonPython312Libsite-packagesundetected_chromedriver_init.py”, line 258, in init
self.patcher.auto()
File “C:UsersALEXAppDataLocalProgramsPythonPython312Libsite-packagesundetected_chromedriverpatcher.py”, line 178, in auto
self.unzip_package(self.fetch_package())
File “C:UsersALEXAppDataLocalProgramsPythonPython312Libsite-packagesundetected_chromedriverpatcher.py”, line 310, in unzip_package
os.rename(os.path.join(self.zip_path, exe_path), self.executable_path)
Source code by GPT:
import time
import threading
import undetected_chromedriver as uc
from rich import print
def run_session(platform, session_number):
# Launching the browser
options = uc.ChromeOptions()
options.add_argument("--window-size=518,600")
driver = uc.Chrome(options=options, use_subprocess=True)
if platform == "example":
driver.get('https://example.com/')
elif platform == "example_1":
driver.get('https://example.com/')
elif platform == "example_2":
driver.get('https://example.com/')
print(f"Session number {session_number + 1} has launched")
# Main program
while True:
print("n[green]❤️[white] How much sessions :")
session_count = int(input("==> Enter the response in the console : "))
print("n[green]❤️[white] Select the site you want to [green]visit [white]: [green] example / example_1 / example_2")
platform = input("==> Enter the response in the console : ")
if platform in ["example", "example_1", "example_2"]:
break
else:
print("n❗️ [white]ENTER [red]example[white] or [red]example_1[white] or [red]example_2")
# If ok
print(f"[green]==> [white]The site is selected: [green]{platform}")
# Start sessions in parallel
threads = []
for i in range(session_count):
thread = threading.Thread(target=run_session, args=(platform, i))
threads.append(thread)
thread.start()
# Wait for all sessions to complete
for thread in threads:
thread.join()
# We display a completion message
print("All sessions are running")
while True:
time.sleep(1)