I found this simple example demonstrating how to use threading to parallelize opening multiple chrome sessions with selenium.
from selenium import webdriver
import threading
import time
def test_logic():
driver = webdriver.Chrome()
url = 'https://www.google.de'
driver.get(url)
# Implement your test logic
time.sleep(2)
driver.quit()
N = 5 # Number of browsers to spawn
thread_list = list()
# Start test
for i in range(N):
t = threading.Thread(name='Test {}'.format(i), target=test_logic)
t.start()
time.sleep(1)
print(t.name ' started!')
thread_list.append(t)
# Wait for all threads to complete
for thread in thread_list:
thread.join()
print('Test completed!')
I tested it and it works. However if I modify the test_logic
function to include a variable, i.e. j
:
def test_logic(j):
driver = webdriver.Chrome()
url = 'https://www.google.de'
driver.get(url)
# Implement your test logic
time.sleep(j)
driver.quit()
and the corresponding part of threading to:
t = threading.Thread(name='Test {}'.format(i), target=test_logic(i))
the code will stop working in parallel and just runs sequentially.
I don't know what I might have not considered and therefore will be very grateful if anybody can give me some advices. Many thanks!
CodePudding user response:
target=test_logic(i)
is invoking the function test_logic
and give the return value to the thread.
You may want to do:
t = threading.Thread(name='Test {}'.format(i), target=test_logic, args=[i])
where target
is the name of the function, and args
is the arguments list for the function.
If you function has 2 args, like def test_logic(a,b)
, the args
should contain 2 values.
More info in Python Thread Documentation
CodePudding user response:
You have to pass arguments to function as below:
t = threading.Thread(name='Test {}'.format(i), target=test_logic, args=(i,))