首页 > 解决方案 > How to run headless firefox browser on remote server over SSH connection?

问题描述

I have a remote server and I wish to run a headless session of Firefox there. I login into the remote server and execute the command. Even if the commands are headless, still it opens my machine's Firefox and performs actions within it. Any idea what could be the reason? I wish to perform these actions remotely without my display machine (like my laptop) being connected to it.

from selenium.webdriver import Firefox
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from selenium.webdriver.support import expected_conditions as expected
from selenium.webdriver.support.wait import WebDriverWait

if __name__ == "__main__":
    options = Options()
    options.add_argument('-headless')
    driver = Firefox(executable_path='/path/to/geckodriver', firefox_options=options)
    wait = WebDriverWait(driver, timeout=10)
    driver.get('http://www.google.com')
    wait.until(expected.visibility_of_element_located((By.NAME, 'q'))).send_keys('headless firefox' + Keys.ENTER)
    wait.until(expected.visibility_of_element_located((By.CSS_SELECTOR, '#ires a'))).click()
    print(driver.page_source)
    driver.quit()

标签: python-3.xseleniumfirefox

解决方案


I resolved it myself as follows:

First run this in terminal

sudo apt-get install xvfb
sudo pip3 install pyvirtualdisplay

Then add following lines to your code

from pyvirtualdisplay import Display
display = Display(visible=0,size=(1024,768))
display.start()

And my browser configuration looks like this:

cap = DesiredCapabilities().FIREFOX
cap["marionette"] = False
display = Display(visible=0,size=(1024,768))
display.start()
options = Options()
options.set_headless(headless=True)
binary = FirefoxBinary("/home/ubuntu/firefox/firefox")
options.add_argument("-headless")
browser = Firefox(firefox_options=options, executable_path='/home/ubuntu/Documents/sourcecode/geckodriver',firefox_binary=binary,capabilities = cap )

推荐阅读