使用selenium库时,报错WebDriverException: Message: Process unexpectedly closed with status 1

检查当前目录下的geckodriver.log日志,如果内容如下: Error: GDK_BACKEND does not match available displays 或 Error: no DISPLAY environment variable specified 表示没有可供显示的环境,因为是在命令行模式下(无头模式)试图启动firefox。此时需要为selenium的webdriver.Firefox设置其选项,如下:

from selenium import webdriver from selenium.webdriver import FirefoxOptions opts = FirefoxOptions() opts.add_argument("--headless") browser = webdriver.Firefox(firefox_options=opts) browser.get('http://example.com')