Python Selenium Firefox – how to enable headless-mode as part of a class/object?

Question:

I have the following code:

options = Options()
options = options.set_headless( headless=True)

class Sel_Driver():

    def __init__(self):
        self.driver = webdriver.Firefox(firefox_options=options)

I can then use self.driver.get(url) as part of a method to open urls I feed in. This works – I can feed in and open the URLs, but they don’t in headless mode.

(I initially defined the driver as self.driver = webdriver.Firefox(firefox_options=Options().set_headless(headless=True) – but that didn’t work, so I tried it as above).

What am I missing? I don’t understand why the driver is able to open pages, but the options aren’t enabled.

Asked By: ron_g

||

Answers:

Please try following code :

options = Options()
options.add_argument("--headless")
driver = webdriver.Firefox(firefox_options=options)
Answered By: slckayhn

This will work for you for sure. Try it.Please specify the path of the driver. It is for chrome change it to firefox.

from pyvirtualdisplay import Display
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument("--headless")
driver = webdriver.Chrome(chrome_options=options, executable_path="C:\Users\Username\Downloads\chromedriver.exe")
print("Firefox Headless Browser Invoked")
driver.get('https://www.facebook.com/')
jks = driver.find_element_by_id("email").get_attribute("class")
print(jks)
driver.quit()
Answered By: Jaikrishna Sharma