0

I want to run the code twice at the same to save time. I am a beginner and I was doing some research on that and get the word multithreading and heard about pytest library but I have no idea how to do that and even I couldn't found the example code. Please help me! I am waiting for your answer

import selenium
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from shutil import which
import time
import pandas as pd
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
Links = []
chrome_path = which('chromedriver')
driver = webdriver.Chrome(executable_path=chrome_path)
driver.maximize_window()

driver.get('https://www.google.com')

text = driver.find_element_by_xpath('//input[@class="gLFyf gsfi"]')
text.send_keys('Hello')

driver.find_element_by_xpath('//div[@class="FPdoLc tfB0Bf"]//input[1]').click()
time.sleep(3)

driver.close()

I want to run twice at same time? Anybody help me

Noob Gamer
  • 45
  • 1
  • 1
  • 6
  • Why not use multithreading? – undetected Selenium Dec 28 '20 at 14:45
  • Does this answer your question? [How to run multiple Selenium Firefox browsers concurrently?](https://stackoverflow.com/questions/16551111/how-to-run-multiple-selenium-firefox-browsers-concurrently) – dwb Dec 28 '20 at 16:22

2 Answers2

0

Refactor your whole selenium code into a class/method that accepts the instance of the webdriver as input (this is not mandatory, just separation of interests).

Then you run that method as how many threads you want.

Here is an example based on your codes, also added code to get results from each thread.

import time

import concurrent.futures
from selenium import webdriver


def task(driver):
    driver.get('https://www.google.com')
    text = driver.find_element_by_xpath('//input[@class="gLFyf gsfi"]')
    text.send_keys('Hello')
    driver.find_element_by_xpath('//div[@class="FPdoLc tfB0Bf"]//input[1]').click()
    time.sleep(3)
    driver.close()


if __name__ == '__main__':
    futures = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:
        for i in range(3):
            driver = webdriver.Chrome(executable_path="./chromedriver")
            driver.maximize_window()
            futures.append(executor.submit(task, driver))
    for future in futures:
        print(future.result())
OranShuster
  • 476
  • 2
  • 12
0

You can always use "Jupyter Notebooks" then you can save-as your script with a new name and run them both at the same time.

DBraun
  • 38
  • 1
  • 7