DoctorEvil
DoctorEvil

Reputation: 473

Threading and Selenium

I'm trying to make multiple tabs in Selenium and open a page on each tab simultaneously. Here is the code.

CHROME_DRIVER_PATH = "C:/chromedriver.exe"

from selenium import webdriver
import threading
driver = webdriver.Chrome(CHROME_DRIVER_PATH)

links = ["https://www.google.com/",
         "https://stackoverflow.com/",
         "https://www.reddit.com/",
         "https://edition.cnn.com/"]

def open_page(url, tab_index):
    driver.switch_to_window(handles[tab_index])
    driver.get(url)
    return

# open a blank tab for every link in the list
for link in range(len(links)-1 ): # 1 less because first tab is already opened
    driver.execute_script("window.open();")

handles = driver.window_handles # get handles

all_threads = []
for i in range(0, len(links)):
    current_thread = threading.Thread(target=open_page, args=(links[i], i,))
    all_threads.append(current_thread)
    current_thread.start()

for thr in all_threads:
    thr.join()


Execution goes without errors, and from what I understand this should logically work correctly. But, the effect of the program is not as I imagined. It only opens one page at a time, sometimes it doesn't even switch the tab... Is there a problem that I'm not aware of in my code or threading doesn't work with Selenium?

Upvotes: 0

Views: 1748

Answers (1)

Andersson
Andersson

Reputation: 52665

There is no need in switching to new window to get URL, you can try below to open each URL in new tab one by one:

links = ["https://www.google.com/",
         "https://stackoverflow.com/",
         "https://www.reddit.com/",
         "https://edition.cnn.com/"]

# Open all URLs in new tabs
for link in links:
    driver.execute_script("window.open('{}');".format(link))

# Closing main (empty) tab
driver.close()

Now you can handle (if you want) all the windows from driver.window_handles as usual

Upvotes: 3

Related Questions