skip to Main Content

I have 40 Python unit tests and each of them open a Selenium driver as they are separate files and cannot share the same driver.

from selenium import webdriver
webdriver.Firefox()

The above commands will take the focus to the new opened window. For example, if I am on my editor and typing something, in the middle of my work, suddenly a selenium browser is opening and Linux switch to that window. I am not sure if Windows or Mac have a similar problem or not.

This means that every time I run a unit, I cannot use my computer as it keeps switching away from the application that I am currently using.

How can I tell Selenium not to switch to the opened window?

2

Answers


  1. Here is an example of running Selenium/Firefox on linux, in headless mode. You can see various imports as well – gonna leave them there. Browser will start in headless mode, will go to ddg page and print out the page source, then quit.

    from selenium.common.exceptions import NoSuchElementException, TimeoutException
    from selenium import webdriver
    from selenium.webdriver.firefox.service import Service
    from selenium.webdriver.common.keys import Keys
    from selenium.webdriver.firefox.options import Options as Firefox_Options
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support.ui import Select
    from selenium.webdriver.support import expected_conditions as EC
    
    firefox_options = Firefox_Options()
    
    firefox_options.add_argument("--width=1280")
    firefox_options.add_argument("--height=720")
    firefox_options.headless = True
    
    driverService = Service('chromedriver/geckodriver') ## path where geckodriver is
    
    browser = webdriver.Firefox(service=driverService, options=firefox_options)
    wait = WebDriverWait(browser, 20)
    
    browser.get('https://duckduckgo.com')
    print(browser.page_source)
    browser.quit()
    

    Browser can also take screenshots while in headless mode, if any unit test requires it.

    A reasonably well structured documentation for Selenium can be found at https://www.selenium.dev/documentation/ (with some gaps, of course, but generally decent).

    Login or Signup to reply.
  2. You can run your Selenium drivers in headless mode. This will prevent moving focus on opened by Selenium browsers and will not disturb you working on your PC machine.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search