我有一个远程服务器,我希望在那里运行一个无头的Firefox会话。我登录到远程服务器并执行命令。即使命令没有头,它仍然会打开我机器的Firefox并在其中执行操作。知道是什么原因吗?我希望在不连接显示设备(例如笔记本电脑)的情况下远程执行这些操作。
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()
答案 0 :(得分:0)
我自己解决了以下问题:
首先在终端上运行
sudo apt-get install xvfb
sudo pip3 install pyvirtualdisplay
然后在代码中添加以下行
from pyvirtualdisplay import Display
display = Display(visible=0,size=(1024,768))
display.start()
我的浏览器配置如下:
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 )