简体   繁体   中英

Python Selenium new tabs do things at the same time

I want to open with selenium a website where you search for something in 5 different tabs. But when I run it it searching one by one. How can I do it at the same time?

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
PATH = 'C:\Program Files (x86)\chromedriver.exe'
driver = webdriver.Chrome(PATH)
for i in range(5):
    driver.execute_script(f"window.open('about:blank', 'tab{i}');")
    driver.switch_to.window(f"tab{i}")
    driver.get('https://www.techwithtim.net/')
    new = driver.find_element_by_class_name('search-field')
    new.send_keys('Hi')
    new.send_keys(Keys.RETURN)

What should I do?

Thanks.

If you want to run multiple tests at the same time, then I suggest having multiple instances (ie multiple windows) of webdriver since it is much easier to manage with respect to having multiple tabs on the same window.

This is a simple example showing how to spawn multiple simultaneous tests using the threading module. The code will fire up 3 Chrome browsers, open ecosia.org and write something in the search bar.

import time
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.service import Service
import threading

def test_instance():
    driver = webdriver.Chrome(service=Service(your_chromedriver_path))
    driver.get('https://ecosia.org')
    el = driver.find_element(By.CSS_SELECTOR, 'input[type=search]')
    for i in range(10):
        el.send_keys(i)
        time.sleep(1)
    driver.quit()

N = 3   # Number of browsers to spawn
thread_list = list()

# Start test
for i in range(N):
    t = threading.Thread(name=f'Test {i}', target=test_instance)
    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')

Output

Test 0 started
Test 1 started
Test 2 started
Test completed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM