python-3.x - 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()
解决方案
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 )
推荐阅读
- c# - 从 asp.net 核心控制台应用程序运行网站
- c# - 在模块化架构中制作数据访问层的正确方法?
- multithreading - Kotlin 协程不会立即编译(挂起函数?)
- c# - 每个对象都有相同的数组
- php - 正则表达式查找和替换印度字符
- mysql - 按每个房间的最近聊天对聊天室进行排序的最佳方法是什么
- java - 使用打开的 localhost 连接到 Java 服务器不起作用
- spring-boot - @Timed 注释不适用于请求范围的 bean?
- php - PHP 检查 assoc 数组的键,如果存在,将值提高 1
- wordpress-gutenberg - Wordpress Gutenberg - 嵌套子元素