Firefox browser not running in headless mode

Help needed with Firefox headless mode

I’m a beginner in coding and I’m trying to get Firefox to run in headless mode. Although I managed to avoid errors when launching the browser, the window still appears on my screen. I’m working on Windows 10 with Python 3.7.

Below is the modified code I am using:

import random
import time
from selenium import webdriver
from selenium.webdriver.firefox.options import Options

def search_amazon():
    keywords = ['laptop', 'smartphone', 'headphones']
    query = random.choice(keywords)
    
    firefox_options = Options()
    firefox_options.add_argument('--headless')
    
    browser = webdriver.Firefox(executable_path='C:\webdriver\geckodriver.exe', options=firefox_options)
    
    url = f'https://www.amazon.de/s?k={query}'
    browser.get(url)
    
    time.sleep(5)
    browser.quit()

search_amazon()

Any suggestions on why the browser window is still visible? Thanks for your help!

hey there! i’ve had similar issues. try adding firefox_options.headless = True before creating the browser instance. also, make sure ur geckodriver is up to date. sometimes older versions don’t play nice with headless mode. good luck with ur project!

I’ve worked extensively with Selenium and headless browsers, and I can tell you that sometimes Firefox can be finicky with headless mode. One thing that’s worked for me is explicitly setting the ‘moz:firefoxOptions’ capability. Try modifying your code like this:

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities

firefox_options = Options()
firefox_options.add_argument(‘-headless’)

caps = DesiredCapabilities().FIREFOX
caps[‘marionette’] = True
caps[‘moz:firefoxOptions’] = {‘args’: [‘-headless’]}

browser = webdriver.Firefox(executable_path=‘C:\webdriver\geckodriver.exe’, options=firefox_options, capabilities=caps)

This approach has consistently worked for me across different setups. If you’re still having issues, it might be worth checking your Firefox and geckodriver versions for compatibility. Hope this helps!

I’ve encountered this problem before. One thing to check is your Firefox browser version. Ensure it’s compatible with the geckodriver you’re using. Additionally, try adding the argument ‘–disable-gpu’ to your options. This can sometimes resolve visibility issues in headless mode. If the problem persists, consider using a different webdriver like Chrome, which tends to be more reliable for headless operations. Lastly, double-check that you’re not inadvertently calling any functions that might force the browser to display. Keep at it - headless mode can be tricky to set up initially, but it’s worth the effort for automated testing.