Hey everyone! I’m new to coding and I’m having trouble with headless browsers. I tried Chrome first but ran into errors. Now I’m using Firefox and it’s working better, but the browser window is still showing up on my screen. I thought headless mode was supposed to hide it?
I’m on Windows 10 and using Python 3.7. Here’s my code:
import random
import time
from selenium import webdriver
from selenium.webdriver.firefox.options import Options
def browse_amazon():
search_terms = ['laptop', 'headphones', 'smartwatch']
query = random.choice(search_terms)
firefox_options = Options()
firefox_options.add_argument('--headless')
browser = webdriver.Firefox(executable_path='C:\webdriver\geckodriver.exe', options=firefox_options)
browser.get(f'https://www.amazon.de/s?k={query}')
time.sleep(5)
browser.quit()
browse_amazon()
Can anyone help me figure out why the browser is still visible? Thanks in advance!
I’ve encountered similar issues with Firefox headless mode on Windows. One thing that worked for me was setting the MOZ_HEADLESS environment variable. Try adding these lines before initializing your WebDriver:
import os
os.environ[‘MOZ_HEADLESS’] = ‘1’
This tells Firefox to run in headless mode at the system level. Another trick is to use the headless attribute directly instead of add_argument:
firefox_options.headless = True
If you’re still seeing the browser, you might need to use a virtual display. The pyvirtualdisplay library worked well for me. You’d need to install it and Xvfb, then wrap your browser code in a virtual display. It’s a bit more setup, but it solved the visibility issue completely in my case.
Hope this helps! Let me know if you need any clarification on implementing these solutions.
I’ve run into this issue before with Firefox on Windows. Have you tried setting the MOZ_HEADLESS environment variable? Add these lines before initializing your WebDriver:
import os
os.environ[‘MOZ_HEADLESS’] = ‘1’
This tells Firefox to run in headless mode at the system level. If that doesn’t work, you might need to use a virtual display. The pyvirtualdisplay library is good for this, but it requires some additional setup.
Another thing to check is your Firefox and Geckodriver versions. Make sure they’re compatible, as mismatches can cause unexpected behavior.
Lastly, double-check that no other applications are interfering with Firefox’s headless mode. Sometimes background processes can cause issues.